How to submit selected rows from DataTables in a form

I am using DataTables multi item selection and like to submit the selected rows to my form.

Of course, I could manually create an input element for each row in my table:

<input type="hidden" id="row_0" name="par" value="456" disabled="disabled" />
<input type="hidden" id="row_1" name="par" value="876" disabled="disabled" />
...

and then toggle the disabled attribute based on the row selection. Something like this:

for (let row of table.rows({ selected: true })) {
  $(`#row_${row.index()}`).removeAttr("disabled");
}

But maybe there is an easier solution which requires less coding, I did not find any.

TypeScript Error: “Cannot redeclare block-scoped variable ‘x'” when variables are in different files [duplicate]

TypeScript Error: “Cannot redeclare block-scoped variable ‘x'” when variables are in different files

I’m working on a Node.js/TypeScript project and I’m encountering a strange error. I have two separate TypeScript files with variables that have the same name, but TypeScript is complaining about redeclaration.

My setup:

File B (module-practice.ts):

const x = 'Variable X';
console.log(x);
// other code...
module.exports = () => {
  console.log('I am X ......');
  console.log(x);
};

File A (index.ts):

const fn = require('./module-practice');
console.log(fn);
const x = 'Again Variable X';  // Error happens here
fn();

The error I’m getting:

Cannot redeclare block-scoped variable 'x'.

What I’ve tried:

When I add export {}; in file A (index.ts), the error goes away.

My question:

  1. Why am I getting this error when the variables are in completely different files?
  2. Why does adding export {}; fix the issue?
  3. Is this the correct solution or is there a better approach?

I’m confused because I thought each file would have its own scope for variables, especially.

How To Keep user logged in on refresh but log out on browser/tab close in Angular?

How can i make my angular application maintain the user session on page refresh but automatically log out the user when the browser tab or windows is closed?

What I Tried

  1. I used the beforeunload event in Angular (window.addEventListener(‘beforeunload’, …)) to know when the tab is closing.

  2. I called my authService.logout() inside this event to log the user out.

  3. But I noticed this also runs when the page refreshes or when the user navigates away, which I don’t want.

  4. I also checked the MDN docs and tried using returnValue for the unload event, but it shows the generic browser message and still activates on refresh.

What I Expected

  1. When the user refreshes the Angular page, the session/token should be kept so they remain logged in.

  2. When the user closes the browser or tab, the app should log them out automatically, clearing tokens/session both locally and on the backend.

I wanna make my Vanilla HTML, CSS, and JavaScript E-Commerce Website comes with Multi-Languages dropdown list

I wanna make a dropdown list with all languages and the selected language be translated automatically like using Google Translate API instead of make [data-en] or [data-ar] attributes to translate text contents manually.

This is an Example of the translation Way I do..

// Language Switcher
    const langButtons = document.querySelectorAll('.lang-btn');
    
    langButtons.forEach(button => {
        button.addEventListener('click', function() {
            const lang = this.getAttribute('data-lang');
            
            // Update active button
            langButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // Update language attributes
            document.body.setAttribute('data-lang', lang);
            document.body.setAttribute('dir', lang === 'ar' ? 'rtl' : 'ltr');
            
            // Update all text elements
            updateTextContent(lang);
        });
    });

    // Function to update text content based on language
    function updateTextContent(lang) {
        const elements = document.querySelectorAll('[data-en], [data-ar]');
        
        elements.forEach(element => {
            if (lang === 'en') {
                if (element.hasAttribute('data-en')) {
                    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                        element.setAttribute('placeholder', element.getAttribute('data-en'));
                    } else {
                        element.textContent = element.getAttribute('data-en');
                    }
                }
            } else if (lang === 'ar') {
                if (element.hasAttribute('data-ar')) {
                    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                        element.setAttribute('placeholder', element.getAttribute('data-ar'));
                    } else {
                        element.textContent = element.getAttribute('data-ar');
                    }
                }
            }
        });
    }
<header class="header">
        <div class="container">
            <div class="header-content">
                <div class="logo">
                    <h2 data-en="ABC Therapy" data-ar="ABC ثيرابي">ABC Therapy</h2>
                </div>
                <nav class="navigation">
                    <a href="#home" class="nav-link active" data-en="Home" data-ar="الرئيسية">Home</a>
                    <a href="#testimonials" class="nav-link" data-en="Testimonials" data-ar="آراء المرضى">Testimonials</a>
                    <a href="#services" class="nav-link" data-en="Services" data-ar="الخدمات">Services</a>
                    <a href="#about" class="nav-link" data-en="About" data-ar="من نحن">About</a>
                    <a href="#contact" class="nav-link" data-en="Contact" data-ar="تواصل معنا">Contact</a>
                </nav>
                <div class="header-actions">
                    <button class="appointment-btn" data-en="Book Appointment" data-ar="احجز موعد">Book Appointment</button>
                </div>
            </div>
        </div>
    </header>

HTML Document to tranlate only from English to Arabic or vice versa

download all pdfs with playwright not working

here is the code

  const browser = await chromium.launch();
  console.log('browser',browser);
  const context = await browser.newContext({
    acceptDownloads: true
  });
  const page = await context.newPage();
  await page.goto(pageUrl, { waitUntil: 'domcontentloaded' });

  // Get all PDF links (anchors ending with .pdf)
  const pdfLinks: string[] = await page.$$eval(
    "a[href$='.pdf']",
    anchors => anchors.map(a => (a as HTMLAnchorElement).href)
  );

  console.log(`Found ${pdfLinks.length} PDF(s).`);

  for (const rawLink of pdfLinks) {
    const pdfUrl = new URL(rawLink, pageUrl).toString();
    // Open link in a new tab to trigger download
    const [download] = await Promise.all([
      page.waitForEvent('download'),
      page.click(`a[href='${pdfUrl}']`).catch(async () => {
        const pdfPage = await context.newPage();
        await pdfPage.goto(pdfUrl);
        await pdfPage.close();
      })
    ]);
    const urlObj = new URL(pdfUrl);
    const filename = path.basename(urlObj.pathname);
    const filepath = path.join(downloadDir, filename);
    await (download as Download).saveAs(filepath);
    console.log(`Downloaded: ${filepath}`);
  }

  await browser.close();

Expected result is all the pdf will be downloaded but in reality browser only opens the first pdf but not downloading it, the rest of pdf pages are not opening and the browser just closed down.

any idea how to solve it?

Javascript default settings

I’m building an collection of functions and need to have this collection have default options, which the user can set on use.

(function (blackout, $, undefined) {
    blackout.text = "Please wait ...";
    blackout.timeout = 1000;
    blackout.img = "/Content/Images/loader.png";
    var defaultOptions = {
        text: "Please wait...",
        timeout: 1000,
        img: "/Content/Images/loader.png",
    };

    blackout.show = function ({text = blackout.defaultOptions.text, timeout = blackout.defaultOptions.timeout, img = blackout.defaultOptions.img}) {
        return this;
    }
    blackout.hide = function () {
        return this;
    }
}(Skd.blackout = Skd.blackout || {}, jQuery));

What I need is the option to call Skd.blackout.show() executing with default options or Skd.blackout.show({ text: "Hi Stack Overflow" }) showing the same, but with a differenct text.

How do I accomplise this?

I’ve tried a bunch of approaces and a hitting the dev-wall every time

Import issue in the react file

When I’m importing react to the index.js this shows me a invisible line and when I’m saving the code it’s getting Total invisible. When I’m running the html file the output is not showing. I’ve stored all the files in my single folder

I’ve installed npm, react, react-dom, I’ve also run the npm run start,

Restricting the Code with only one particular table

I have following JS code and working perfectly if it is on each and every html page (containing two of three Tables) of my project. But when i placed that code in JS external file and linked that file with html pages, it is triggering each and every table on a html page. I tried to restrict it with only MyTable3, but if I click in any table of the page, the code starts working. Is it possible to have the code in an external JS file and it should only work with a particular Table i.e. myTable3. Thanks.

var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
    cells[i].addEventListener('click', clickHandler);
}

function clickHandler()
{
    document.getElementById("tulip").value = (this.textContent);
    document.getElementById("tulip").click(); 
}

Cannot read properties of undefined (reading ‘loadVideoById’)

Ive been doing an audio player that uses youtube links for my personal website (of which I used the code from Max Zheng How to play only the audio of a Youtube video using HTML 5?), and a few days ago I finally managed to make it work. But there is a problem: the function I made to change songs became way too long:

      function checkin(z){
        document.getElementById("x").innerHTML = z;
        if (z == 1) {
          document.getElementById("nome_musica").innerHTML = "Engenheiros do Hawaii - Infinita Highway (ao vivo)";
      //substitute the text above with the name of the song
          id_video = a;
          //YT.Player.load();
          // refresh();
      //substitute the variable with your song
        }else if (z == 2){
          document.getElementById("nome_musica").innerHTML = "They Might Be Giants - Istambul(not Constantinople)";
          id_video = d;
         //player.load();
          ytPlayer.loadVideoById(id_video);
          // refresh();
        }else if (z == 3){
          document.getElementById("nome_musica").innerHTML = "Kocchi no Kento - Hai Yorokonde";
          id_video = c;
          //player.load();
         ytPlayer.loadVideoById(id_video);
          // refresh();
        }else{
          document.getElementById("error").innerHTML = "error in the system";
        }
      }

I tried to make a For loop as well as two separate arrays (one for the links and another for the song titles) so it repeats comparing the song number n times, with n being the arrays length.

      const links = [a,d,c,f];
      const nomes = ["Engenheiros do Hawaii - Infinita Highway (ao vivo)","They Might Be Giants - Istambul(not Constantinople)","Kocchi no Kento - Hai Yorokonde","the pillows - THE LAST DINOSAUR"];

      var inicio = checkin(xe);

      function checkin(n){
        document.getElementById("x").innerHTML = n;
        for (let i = 1; i < links.length; i++) {
          if (n===i){
            let j = i - 1;
            id_video = links[j].toString();
            
            ytPlayer.loadVideoById(id_video);//"jLdAuGarfM0");
            document.getElementById("nome_musica").innerHTML = nomes[j].toString();
          }else{
            continue;
          }
        }
      }

But when I try this loop, the console says Cannot read properties of undefined (reading ‘loadVideoById’); although the loadVideoById worked perfectly fine in the other function. What the hell is the issue here? Is it just that it doesnt work inside for loops?
I can work it with the other function, but I would prefer if I could use the one with a For loop.

How Do I Use Proxies with Puppeteer and a Local Chrome Instance?

I’m using Puppeteer and JS to write a web scraper. The site I’m scraping is pretty intense, so I need to use a local chrome instance and a residential proxy service to get it working. Here’s my basic setup.

const chromeProcess = spawn(chromePath, [
    `--remote-debugging-port=${PORT}`,
    `--user-data-dir=${userDataDir}`,
    `--proxy-server=${proxyUrl}`,
    "--no-first-run",
    "--no-default-browser-check",
    "--disable-extensions",
    "--start-maximized",
    "--disable-features=IsolateOrigins,site-per-process"
  ], { stdio: "ignore" });

  let browser = await puppeteer.connect({ browserURL: `http://127.0.0.1:${PORT}` });
  let page = await browser.newPage();

I’ve been getting a multitude of errors trying to get the proxy service working, however, (like net::ERR_NO_SUPPORTED_PROXIES) where the page won’t load, or will show a “page not found” error in the browser. I’ve tried tunneling with mitmproxy with no luck, so I’m just not sure what’s possible at this point.

Does anyone have any insight into using proxies with a local chrome instance? Is this even possible?

Using navigator.clipboard to write multiple entries to clipboard

I have up to four form text inputs that I’m trying to get copied to the windows clipboard as individual entries. Using navigator.clipboard.writeText it will successfully copy any one entry, but multiple calls simply overwrite the same clipboard entry.

A simplified code extract:

`function aFunction() {
    let inputElm1 = document.createElement("input");
    inputElm1.id = "inputElm1";
    inputElm1.type = "text";
    someContainerElement.appendChild(inputElm1);

    let inputElm2 = document.createElement("input");
    inputElm2.id = "inputElm2";
    inputElm2.type = "text";
    someContainerElement.appendChild(inputElm2);

    let copyButton = document.createElement("button");
    copyButton.id = "copyButton";
    copyButton.innerHTML = "Copy All To Clipboard";
    copyButton.addEventListener("click", copyButtonClick );
    someContainerElement.appendChild(copyButton);
}
function copyButtonClick(){
    let sourceElm1 = document.getElementById("inputElm1");
    sourceElm1.select();
    navigator.clipboard.writeText(sourceElm1.value);
    
    let sourceElm2 = document.getElementById("inputElm2");
    sourceElm2.select();
    navigator.clipboard.writeText(sourceElm2.value);    
}`

Then when using the Windows Key + V to open the clipboard history only the last entry is present. (in the example sourceElm2 value).
I can manually Ctrl-C on each input in succession and all entries appear in the clipboard history.
I’m sure I’m missing something, just can’t determine what.

Odoo 18 POS – Display Only Combo Products with Total Price and Order Date on Receipt

In my Odoo 18 POS, I want to customize the receipt so that:

Only products of type “combo” are displayed.

The individual items included in the combo are not listed separately.

The displayed price is the total price of the combo, not the sum of the child products.

The receipt layout remains the default Odoo POS layout.

The order date should be displayed, not just the payment timestamp.

I have tried overriding OrderReceipt using a CustomOrderReceipt component, but I encounter errors such as OwlError or Cannot read properties of undefined when filtering lines or accessing paymentlines.

I am looking for an approach or working example to:

Filter order lines to show only combos.

Display the total price of the combo.

Show the order date.

Avoid Owl errors caused by missing data (e.g., payment_method undefined).

Any advice or working examples would be greatly appreciated.

My template
[text](

<?xml version="1.0" encoding="UTF-8"?>
<templates id="template" xml:space="preserve">

  <!-- Surcharge du template OrderReceipt -->
  <t t-name="pos_receipt_customisation.OrderReceipt" t-inherit="point_of_sale.OrderReceipt" t-inherit-mode="primary">

    <xpath expr="//OrderWidget" position="replace">

      <!-- Filtrer uniquement les lignes de type combo (exclure enfants) -->
      <t t-set="combo_lines" t-value="props.data.orderlines.filter(line => line.is_combo)"/>

      <div class="order-container d-flex flex-column flex-grow-1 overflow-y-auto text-start">
        <t t-foreach="combo_lines" t-as="line" t-key="line.id">
          <li class="orderline position-relative d-flex align-items-center p-2 lh-sm cursor-pointer px-0">
            <div class="product-order"></div>
            <div class="d-flex flex-column w-100 gap-1">
              <div class="d-flex justify-content-between">
                <div class="product-name d-inline-block flex-grow-1 fw-bolder pe-1 text-truncate">
                  <span class="text-wrap"><t t-esc="line.productName"/></span>
                </div>
                <div class="product-price price fw-bolder">
                  <t t-esc="line.price_total ? props.formatCurrency(line.price_total) : props.formatCurrency(line.price)"/>
                </div>
              </div>
              <ul class="info-list d-flex flex-column">
                <li class="price-per-unit">
                  <span class="qty px-1 border rounded text-bg-view fw-bolder me-1">
                    <t t-esc="line.qty"/> <t t-esc="line.unit || 'Unité(s)'"/>
                  </span>
                  x <t t-esc="line.price_total ? props.formatCurrency(line.price_total) : props.formatCurrency(line.price)"/> / <t t-esc="line.unit || 'Unité(s)'"/>
                </li>
              </ul>
            </div>
          </li>
        </t>
      </div>

      <!-- Montant total -->
      <div class="pos-receipt-amount receipt-total">
        TOTAL
        <span class="pos-receipt-right-align">
          <t t-esc="props.formatCurrency(props.data.amount_total)"/>
        </span>
      </div>

      <!-- Paiement -->
<div class="paymentlines text-start">
  <t t-foreach="props.data.paymentlines" t-as="line" t-key="line.id">
    <t t-if="line.payment_method">
      <t t-esc="line.payment_method.name"/> 
      <span class="pos-receipt-right-align">
        <t t-esc="props.formatCurrency(line.amount)"/>
      </span>
    </t>
    <t t-else="">
      <span>Autre</span>
      <span class="pos-receipt-right-align">
        <t t-esc="props.formatCurrency(line.amount)"/>
      </span>
    </t>
  </t>
</div>


    </xpath>
  </t>

  <!-- Surcharge ReceiptScreen -->
  <t t-name="pos_receipt_customisation.ReceiptScreen" t-inherit="point_of_sale.ReceiptScreen" t-inherit-mode="extension" owl="1">
    <xpath expr="//OrderReceipt" position="replace">
      <CustomOrderReceipt data="pos.orderExportForPrinting(pos.get_order())" formatCurrency="env.utils.formatCurrency"/>
    </xpath>
  </t>

</templates>

this is the Js:
/** @odoo-module **/

import { patch } from "@web/core/utils/patch";
import { ReceiptScreen } from "@point_of_sale/app/screens/receipt_screen/receipt_screen";
import { OrderReceipt } from "@point_of_sale/app/screens/receipt_screen/receipt/order_receipt";

export class CustomOrderReceipt extends OrderReceipt {
  static template = "pos_receipt_customisation.OrderReceipt";
}

patch(ReceiptScreen, {
  components: { ...ReceiptScreen.components, CustomOrderReceipt },
});

)

What I tried:

I tried to customize the Odoo 18 POS receipt by:

Creating a custom XML template that inherits from point_of_sale.OrderReceipt.

Using an xpath to replace the OrderWidget section and filter only combo products (line.is_combo).

Displaying the combo product name, quantity, and total price, while excluding the products included in the combo.

Adding the total amount and payment lines using props.formatCurrency.

Creating a JavaScript class CustomOrderReceipt extending OrderReceipt and patching ReceiptScreen to include the custom component.

What I was expecting:

The receipt should only show combo products, not their child items.

Each combo should display its total price.

The receipt layout should remain the default Odoo POS style.

The total order amount and payment lines should display correctly.

Ideally, the receipt should also display the order date, not just the payment time.

Currently, instead of this expected behavior, I am getting Owl lifecycle errors and some combo prices or payment methods sometimes don’t display properly.

How can I remove the Error Overlay that obstructs Playwright E2E test assertions

I’m running Playwright E2E tests against a Next.js 15 project. When something goes wrong in dev, Next injects an error overlay (via the element) (see image as an example). That overlay is useful in development, but during Playwright runs it sometimes appears on top of the page and blocks my tests (screenshots, clicks, assertions).

enter image description here

What I want:

For E2E only, I’d like to hide or disable that overlay so tests can continue cleanly (often times these errors are unrelated to the tests i’d like to assert).

What I’ve tried:

I wrote a helper to hide the portal element after page.goto(), but overlays can appear later (after navigation or initial render) so it isn’t reliable, and seems very hacky.

Example test setup:

export async function hideNextJsPortal(page) {
  await page.evaluate(() => {
    const portal = document.querySelector('nextjs-portal');
    if (portal) portal.style.display = 'none';
  });
}

in test sample:

test.beforeEach(async ({ page }) => {
  await page.goto('/');
  await hideNextJsPortal(page);
});

Pressing enter doesn’t run JS function, separate button does work

I’m trying to make a website where a user can input a name, and get a webpage corresponding to that name (if it exists). I’ve got a simple function that when the user presses the submit button, the function works exactly as desired. However, when I’ve tried to update the code so that the user can also press the enter button for the same effect, the code doesn’t run properly, not pulling up the correct window, nor giving the incorrect site or a http error.

This is the js code:

       function showFrame(){
          //show frame
          document.getElementById("Frame").style.display = "flex";
          //set iframe to the name inputted
          var theRaw = document.getElementById("Hog").value;
          theProcessed = "https://chickendragon.neocities.org/Database/" + theRaw;
          document.getElementById("inFrame").src = theProcessed;
          document.getElementById("Database").style.display = "none";
       }

This is the html:

  <!-- Search Bar--> 
  <div class="content" id="Database">
  <form >
    <label for="Hog">Enter file name below:</label><br>
     <input type="text" id="Hog">
  </form>
  <button onclick="showFrame()">Submit</button> <!-- This works-->
  </div>

  <!-- File access-->
  <div class="content" id="Frame">
  <iframe id="inFrame" src= ""></iframe>
  </div>

I’ve tried putting an onsubmit=”showFrame()” but nowhere I slot it seems to work. Additionally, moving the code around to pass the input value into the function also gives similar results.

Javascript ctx.putImageData at an angle for unknown reason

I am writing a program to generate some orbital images. I decided to use js because I have a fair amount of experience with it and its fast to write for prototypes. The issue is that when I go to use ctx.putImageData it is rotated by a -45° angle and the image is stretched.
This is the actually important code:

  genImg(){
    let index = 0;
    for(let y = 0; y <= 400; y++){
      for(let x = 0; x <= 400; x++){
        let lx = (x - 200)*this.step;
        let ly = (200 - y)*this.step;
        this.points.push(this.value(Math.sqrt(Math.pow(lx, 2) + Math.pow(ly, 2)), this.t, Math.atan2(lx,ly))[0]);
      }
    }
    let sclFct = 1000/Math.max(...this.points);
    for(let i = 0; i<= 160000; i++){
      let val = Math.round(this.points[i]*sclFct);
      this.imgDataArr[index] = cmap[val*4]; // R value        
      this.imgDataArr[index + 1] = cmap[val*4 + 1]; // G value
      this.imgDataArr[index + 2] = cmap[val*4 + 2]; // B value
      this.imgDataArr[index + 3] = 255; // A value
      index += 4; 
    }
    let imgData = new ImageData(this.imgDataArr, 400, 400);
    ctx.putImageData(imgData, 0, 0);
  }

The Full code is here. Just off the bat I should mention this is all written in a class. The html is just a canvas element in the <main></main> area that is 400px by 400px. The CSS is just to center everything and give the canvas a border. The function this.value(r,t,p) takes the values r(radius), t(theta) and p(phi). Theta is a constant and radius and phi are calculated from (x,y) cords (see line 7 of the prior code).
enter image description here
In the image you can see where there is the diagonal. The black should be in the center with the other colors radiating out. So far I have tried a 45° rotation to the atan2 function, messing with the css and trying to add a rotation, and rotating the ctx element in code (i.e. using ctx.rotate(Math.PI/4)). This all is very strange to me because I have other projects where I have used the same method without issue. Any ideas would be wonderfull!