Placeholder gets clipped on input element when size attribute is set to its length

For an input element, I am setting placeholder containing 23 characters as below. Using CSS I am setting the font-size to 12px. In Javascript, I am setting the size attribute to the length of the placeholder to ensure that it is displayed completely.

Jsfiddle:
https://jsfiddle.net/b37L4cmh/

Chrome:
enter image description here

As per HTML specification for input size attribute,

The size attribute gives the number of characters that, in a visual rendering, the user agent is to allow the user to see while editing the element’s value.

So, I would expect browser to ensure that full length of placeholder is visible with the above snippet, but it gets clipped.

When I change, the font-size to 13px or 11px, I am able to view the full text of placeholder.

Question:
Why is the placeholder getting clipped for font-size: 12px ?

How to dynamically filter in a range in excel?

I have this filter shown below. It currently filters data from sheetnames from A5, A6, and A7.

How can I change this filter to be dynamic? So if I were to add a value to A8 it would automatically be added to the filter?

=LET(
xml_queries,
TEXTJOIN(“”, TRUE,
IF((INDIRECT(“‘” & A5 & “-Fields’!H6:H206″)=”InProgress”) + (INDIRECT(“‘” & A5 & “-Fields’!H6:H206″)=”Incomplete”) + (INDIRECT(“‘” & A5 & “-Fields’!H6:H206″)=”Problem”),
INDEX(INDIRECT(“‘” & A5 & “-Fields’!A6:A206”), , ),
“”),
IF((INDIRECT(“‘” & A6 & “-Fields’!H6:H206″)=”InProgress”) + (INDIRECT(“‘” & A6 & “-Fields’!H6:H206″)=”Incomplete”) + (INDIRECT(“‘” & A6 & “-Fields’!H6:H206″)=”Problem”),
INDEX(INDIRECT(“‘” & A6 & “-Fields’!A6:A206”), , ),
“”),
IF((INDIRECT(“‘” & A7 & “-Fields’!H6:H206″)=”InProgress”) + (INDIRECT(“‘” & A7 & “-Fields’!H6:H206″)=”Incomplete”) + (INDIRECT(“‘” & A7 & “-Fields’!H6:H206″)=”Problem”),
INDEX(INDIRECT(“‘” & A7 & “-Fields’!A6:A206”), , ),
“”)
),
FILTERXML(“” & xml_queries & “”, “//a”)
)

Are IndexedDB writes actually parallel?

I needed to write 50k+ records to IndexedDB in multiple stores (tables). I noticed, that the more stores you write to, the slower the writes are. After some testing, it seems to me that the writes aren’t actually executed in parallel.

MDN says:

Only specify a readwrite transaction mode when necessary. You can concurrently run multiple readonly transactions with overlapping scopes, but you can have only one readwrite transaction for an object store.

as does W3:

Multiple “readwrite” transactions can’t run at the same time if their scopes are overlapping since that would mean that they can modify each other’s data in the middle of the transaction.

But I am writing to different stores (scopes) so i would expect the writes operations to be parallel too?

This is what i tried. Writing 50k records to store1 takes about 3 seconds as does writing to store2. Writing to both at the same time takes about 6 seconds. So correct me if I’m wrong, but that doesn’t seem to be parallel.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>

    <script>
        let db;

        const request = indexedDB.open('idb_test', 1);

        request.onupgradeneeded = () => {
            const db = request.result;
            db.createObjectStore('store1');
            db.createObjectStore('store2');
        };

        request.onsuccess = () => {
            db = request.result;
        };

        function createMany(storeName) {
            const tx = db.transaction(storeName, 'readwrite');

            for (let i = 0; i < 50000; i++) {
                const key = crypto.randomUUID();
                const val = i.toString();

                tx.objectStore(storeName).put(val, key);
            }

            tx.oncomplete = () => {
                console.timeEnd(storeName);
            };
        }

        function store1() {
            console.time('store1');

            createMany('store1');
        }

        function store2() {
            console.time('store2');

            createMany('store2');
        }

        function bothStores() {
            console.time('store1');
            console.time('store2');

            createMany('store1');
            createMany('store2');
        }
    </script>

    <body>
        <button onclick="store1();">store1</button>
        <button onclick="store2();">store2</button>
        <button onclick="bothStores();">store1 + store2</button>
    </body>
</html>

I also tried this with Web Worker just to see if it made any difference, but with same results.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>

    <script>
        // dev server is needed for this to work
        const worker1 = new Worker('worker.js');
        const worker2 = new Worker('worker.js');

        worker1.onmessage = (event) => {
            console.timeEnd(event.data);
        };
        worker2.onmessage = (event) => {
            console.timeEnd(event.data);
        };

        function store1() {
            console.time('store1');

            worker1.postMessage('store1');
        }

        function store2() {
            console.time('store2');

            worker1.postMessage('store2');
        }

        function bothStores() {
            console.time('store1');
            console.time('store2');

            worker1.postMessage('store1');
            worker2.postMessage('store2');
        }
    </script>

    <body>
        <button onclick="store1();">store1</button>
        <button onclick="store2();">store2</button>
        <button onclick="bothStores();">store1 + store2</button>
    </body>
</html>

worker.js:

let db;

const request = indexedDB.open('idb_test', 1);

request.onupgradeneeded = () => {
    const db = request.result;
    db.createObjectStore('store1');
    db.createObjectStore('store2');
};

request.onsuccess = () => {
    db = request.result;
};

function createMany(storeName) {
    const tx = db.transaction(storeName, 'readwrite');

    for (let i = 0; i < 50000; i++) {
        const key = crypto.randomUUID();
        const val = i.toString();

        tx.objectStore(storeName).put(val, key);
    }

    return tx;
}

self.onmessage = (event) => {
    const storeName = event.data;

    const tx = createMany(storeName);

    tx.oncomplete = () => {
        postMessage(storeName);
    };
};


So I tried profiling.

Chrome profiling

I think it’s pretty clear what’s happening. This is from Chrome 121. I’m pretty sure the grey blobs are the actual writes happening (it just says “Task”).


Firefox was a bit different but still not parallel. Also almost 2x faster than Chrome.

Firefox profiling


So am I doing something wrong or are IndexedDB writes actually not parallel?

Unit Test useFetch Hook

I am getting an Object.dispatchError when I run my unit test for my custom useFetch hook.

The hook:

import { useState, useEffect } from 'react';

const useFetch = (url) => {

  const [data, setData] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);

    const apiCall = async () => {
      try {
        const res = await fetch(url);
        if (!res.ok) throw new Error(`Error - ${res.status}`);
        const json = await res.json();

        setData(json);
        setError(null);
      } catch (err) {
        setError(`useFetch Error!`);
      } finally {
        setLoading(false);
      }
    };

    apiCall();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

My unit test:

  import { renderHook, waitFor } from "@testing-library/react";
  import useFetch from './useFetch';

  it('Should handle no URL provided', async () => {
    const { result } = renderHook(() => useFetch());

    await waitFor(() => {
      expect(result.current.error).toBe("useFetch Error!");
    });
  });

The error:

console.error
Error: AggregateError
  at Object.dispatchError (jsdomlivingxhrxhr-utils.js:63:19)
  at Request.<anonymous> (jsdomlibjsdomlivingxhrXMLHttpRequest-impl.js:655:18)
  at Request.emit (node:events:531:35)
  at ClientRequest.<anonymous> (jsdomlibjsdomlivinghelpershttp-request.js:121:14)
  at ClientRequest.emit (node:events:519:28)
  at Socket.socketErrorListener (node:_http_client:492:9)
  at Socket.emit (node:events:519:28)
  at emitErrorNT (node:internal/streams/destroy:169:8)
  at emitErrorCloseNT (node:internal/streams/destroy:128:3)
  at processTicksAndRejections (node:internal/process/task_queues:82:21) undefined

Maybe it is my waitFor() in the unit test that is not written correctly?
How should I unit test my custom hook?

Cheers!

How to position a JavaScript generated Anchor Tag / Element in an HTML page?

I have a js script that outputs a URL which is used to download a file. (this is just the tail end of a file called data.js script):

const blob = new Blob([csvContent], { type:'text/csv;charset=utf-8,' })
const objUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', objUrl)
link.setAttribute('download', 'export.csv')
link.textContent = 'Export Data'

document.querySelector('body').append(link)

No matter where I put this:

<div>
  <script type="text/javascript">src="data.js"></script>
</div>

It always displays at the top of the page.
What am I missing? I am new to JS but my searches lead me to believe that I need create a custom tag or element. Thanks in advance.

I tried this but still no success:

<script>
  blob.innerHTML = `<a>$</a>${objUrl}`;
</script>

Javascript button already pressed [duplicate]

I’m trying to make a button function that add a field to a form, but when I load the page the field it’s already there and the button is useless.

Here’s the HTML and JS code

let btn = document.querySelector("#btn")
let code_2 = document.querySelector(".code2")

btn.addEventListener("click", add())

function add() {
  code_2.innerHTML += '<br><label>Segundo código:</label><br><br><input type="text"><br><br><button id="btn2">Adicionar Peça</button>'
}
<div class="pecas">

  <div class="peca">

    <h2>Primeira Peça:</h2>
    <form>
      <label>Primeiro código:</label><br><br>
      <input type="text"><br><br>
      <button id="btn">Adicionar Peça</button>

      <div class="code2">

      </div>


    </form>

  </div>

</div>

How can I add data in the middle of the row?

The following are my problem with my code:

  1. It should be editable in the middle of the data, not just the last.
  2. If the data is edited, the BCA total should update for all rows from where the edit occurs up to the last.
  3. Data should be deletable, and when new data is input, it should be updated correctly.

Here is my code in function editData and function saveData

function editData(button) {
    let row = button.parentNode.parentNode;
    let cells = row.cells;

    // Store the current values before editing
    let editedGross = parseFloat(cells[9].innerHTML.replace(/[^0-9.]/g, '')) || 0;
    let editedBIR = parseFloat(cells[10].innerHTML.replace(/[^0-9.]/g, '')) || 0;
    let editedNet = parseFloat(cells[11].innerHTML.replace(/[^0-9.]/g, '')) || 0;
    let editedReceipts = parseFloat(cells[12].innerHTML.replace(/[^0-9.]/g, '')) || 0;

    // Add the previous values back to the current BCA Total/Balance
   
    currentBcaTotalBalance += editedNet;
    currentBcaTotalBalance -= editedReceipts;

    // Enable content editing
    for (let i = 0; i < cells.length - 1; i++) {
        let cell = cells[i];
        cell.contentEditable = "true";
    }

    button.innerHTML = "Save";
    button.onclick = function () {
        saveData(this);
    };
}

            
function saveData(button) {
    let row = button.parentNode.parentNode;
    let cells = row.cells;

    // Disable content editing
    for (let i = 0; i < cells.length - 1; i++) {
        let cell = cells[i];
        cell.contentEditable = "false";
    }

    // Calculate the new Net
    let newGross = parseFloat(cells[9].innerHTML.replace(/[^0-9.]/g, '')) || 0;
    let newBIR = parseFloat(cells[10].innerHTML.replace(/[^0-9.]/g, '')) || 0;
    let newNet = newGross - newBIR;

    // Calculate the new BCA Total/Balance based on the conditions
    let newBcaTotalBalance;
    if (newNet > 0) {
        // Subtract the new Net from the current BCA Total/Balance
        newBcaTotalBalance = currentBcaTotalBalance - newNet;
    } else {
        // Add the new Receipts to the current BCA Total/Balance
        let newReceipts = parseFloat(cells[12].innerHTML.replace(/[^0-9.]/g, '')) || 0;
        newBcaTotalBalance = currentBcaTotalBalance + newReceipts;
    }

    // Update the table cells with the new values
    cells[11].innerHTML = newNet.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    cells[13].innerHTML = newBcaTotalBalance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    cells[14].innerHTML =
        '<button onclick="editData(this)">Edit</button>' +
        '<button onclick="deleteData(this)">Delete</button>';

    button.innerHTML = "Edit";
    button.onclick = function () {
        editData(this);
    };
}

This first picture is the correct calculation.
(https://i.stack.imgur.com/4UPEg.png)
In this second picture, the 3rd row has been edited, and the BCA total/balance should be 300, and the values in the subsequent rows should also be updated.
(https://i.stack.imgur.com/m4CYh.png)

JSR223 Pre-Processor Generate a Value

I have a situation where I am trying to figure out how to get a value that is generated dynamically within the web application. It’s used in pretty much almost every request in the workflow I have been using.

I notice that it is created based on a javascript code within a function that goes along the lines of something like

function getbrowserSecurityPrint() {
 var choices = {
   excludes: {
     'random1' = true,
     'random2' = true,
     'random3' = true,
     'random4' = true,
     'random5' = true,
     'random6' = true,
 }
};

var materials = {};
SecurityPrint2.get(options,functions(materials){
  var values = materials.map(functions(materials) {
   return materials.value; 
}};

SecurityPrintToken = SecurityPrint2.x64hash128(values.join(''), 31);
brand.d.browserSecurityPrint = '{g1}' + SecurityPrintToken;
});
if (!brand.d.ServerProxy.isDestinationLocal()){
  getbrowserSecurityPrint(); 
}
function setSecurityPrint () {
  getbrowserSecurityPrint();
}
function setbrowserSecurityPrint() {
 var element = document.getElementById("GOP");
 if (element != null) {
   document.getElementByID("GOP").value = brand.d.browserSecurityPrint;}; 

Essentially I want the value GOP, but I can’t find it anywhere to correlate it since I assume it is being generated within the source code.

I tried using the JSR223 pre-processor, but I am stuck as I don’t know how to use it to achieve what I want

Javascript POST behaving differently with Safari

I have a web server running from an embedded system, and the user has the option to upload files to the unit using POST, which works great until I use Safari, then it doesn’t seem be waiting for the process to finish before continuing.

Here is the (redacted) code I’m using, called after the user selects a file to upload from a form:

let uploadFormData = new FormData();
uploadFormData.append("file", filesIn.files[0]);
let request = new XMLHttpRequest();
request.open('POST', 'loadWaveMap.cgi?id=' + id);

// Display Progress Bar
request.upload.addEventListener('progress', event => {
  // Add the current progress to the button
  progressBar.innerHTML = 'Uploading... ' + '('
  Math.round((event.loaded / event.total) * 100) + '%)';
  // Update the progress bar
  progressBar.style.background = 'linear-gradient(to right, #25b3FF, #870404 ' +
    Math.round((event.loaded / event.total) * 100) + '%, #e6e8ec ' +
    Math.round((event.loaded / event.total) * 100) + '%)';
});

// once complete, get a confirmation of the received file
request.onreadystatechange = async() => {
  if (request.readyState == 4 && request.status == 200) {
    // Output the response message
    progressBar.innerHTML = 'Done';
    await delay(10000);
    await fetch('./getfileinfo.cgi?id=' + id)
      .then(async(allData) => {
        return await allData.json();
      })
      .then((newFile) => {
        let fileInfoDiv = makeFileElement(newFile);
        currentLineItem.replaceWith(fileInfoDiv);
      });
  }
};
request.send(uploadFormData);

On Chrome this all works perfectly. On Safari, it shows as 100% complete immediately without waiting for a response (it seems).

Any Safari-gurus out there who can see a problem with the above code? If not, it might be how Safari deals with POST behind the scenes that my embedded IP stack isn’t coping with. Any thoughts gratefully received.

How To Detect If The Last Page In History Was Of A Certain Domain

I want to create a 404 page not found button go back to the last page. However, I want the users to stay on the website, so if the history.back() variable is in my subdomain ON ANY OF THE PAGES(subdomain.domain.com) I would redirect them to their last page (history.back), however, if the last page was outside the subdomain, they would be redirected the the homepage.

I tried to define the entire subdomain using the * symbol, but it didn’t work. Here’s what I want it to do:

if (**SOMETHING** === **FULL DOMAIN**) {

history.back();

} else {

/** If Last Page Is Outside Domain **/

window.location.href = "../index.html";

}

Hide URL in network tab of inspect element?

I am building an app but one of the apps components is to guess a secret word. How I have set up everything, the secret word is part of the document on firestore so when the use calls for the firestore document, the secret word is part of the url in the network tab. Is there anyway to hide that word/scramble it so it isn’t super obvious at first glance? Which it is right now.
It’s a reactjs app.
Changing document names at this point would be a ridiculous amount of work and I only recently noticed the problem.

I looked at this question (How to hide data from network tab?) but it didn’t resolve my query.

How to include PDF.js without using Node or a package manager?

I have a static HTML web page that I’d like to include some PDF content in using PDF.js. The content is very simple and static.

How can I include PDF.js without having to use a package manager and build the HTML? I’d simply like to include the relevant JavaScript file(s) and use them. My goal is to simply show a particular page of a PDF in a canvas.

The PDF.js getting started page seems to suggest using a prebuilt at https://cdnjs.com/libraries/pdf.js – but that is just a CSS file, not JavaScript.

I tried using https://mozilla.github.io/pdf.js/examples/ but got CORS errors.

I’m not a web dev, so I may be missing something simple. If so, I ask that you start from the beginning in your answer.

How can make userinfo in DJS?

This is what the console gives me:

TypeError: Cannot read properties of null (reading 'username')
    at Object.execute (C:UsersUSERDocumentsKromeBotthingscommandsutilitymanage.js:13:33)
    at Client.<anonymous> (C:UsersUSERDocumentsKromeBotindex.js:53:17)
    at Client.emit (node:events:514:28)
    at InteractionCreateAction.handle (C:UsersUSERDocumentsKromeBotnode_modulesdiscord.jssrcclientactionsInteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] (C:UsersUSERDocumentsKromeBotnode_modulesdiscord.jssrcclientwebsockethandlersINTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (C:UsersUSERDocumentsKromeBotnode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:355:31)
    at WebSocketManager.<anonymous> (C:UsersUSERDocumentsKromeBotnode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:239:12)
    at WebSocketManager.emit (C:UsersUSERDocumentsKromeBotnode_modules@vladfranguasync_event_emitterdistindex.cjs:282:31)
    at WebSocketShard.<anonymous> (C:[email protected]:1173:51)
    at WebSocketShard.emit (C:UsersUSERDocumentsKromeBotnode_modules@vladfranguasync_event_emitterdistindex.cjs:282:31)

And this is my code:

const { SlashCommandBuilder, EmbedBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName("manage")
        .setDescription("Ban, kick or view info of a user")
        .addUserOption(option =>
            option.setName("target").setDescription("Select a user").setRequired(true)
        ),
    async execute(interaction) {
        const target = interaction.options.getUser('target')
        const userinfo = new EmbedBuilder()
            .setTitle(`${target.username}`)
            .setColor(0xE12424)
            //.setThumbnail(target.displayAvatarURL())
        await interaction.reply({embeds: [userinfo]})
        //await interaction.reply(`Hi ${target}`)
    }
}

I was looking if there was another way, I didn’t find anything. The console: TypeError: Cannot read properties of null (reading ‘username’)

Console Logging .forEach() method

I am trying to get the console to output each number in this array times 2, but it is giving me an error. Here is my code:

const numbers = [1, 2, 3, 4, 5];
const numbersForEach = numbers.forEach(timesTwo)

function timesTwo(value) {
  return value * 2;
}

console.log(numbersForEach)

I don’t want to know if there is another way of doing this because I know there is. What I want to know is why it is not working when I do it this way.

How do I know which AJAX Requests are happening concurrently?

A bit new to performance testing and web architecture in general, but when looking at AJAX Requests that are being called, how do I know which ones being called at the same time versus ones that aren’t? Some of them I can see on developer tools being called like :

“Queued 1.50s” for two AJAX requests. If it’s like a .01s difference does that mean they aren’t called at the same time? I’m trying to figure out which ones I will need to put underneath a parallel controller in JMeter to create the correct network path.