Unable to Detect Change on Dynamically Generated Checkboxes

Description:

I’m facing an issue where dynamically generated checkboxes are not triggering the change event when clicked. To address this, I used $(document).on("change", ".integration-event-checkbox", ...) for event delegation. While this successfully attaches the event, I’m encountering a problem when attempting to retrieve checked checkboxes and update the URL dynamically.

Below is a simplified ( replica not the actual code) version of the code:
HTML File (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Multiple Choice Question with URL</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<body>

  <h2>Which events would you like to include in the URL?</h2>

  <form id="checkboxes">
    <label>
      <input type="checkbox" name="optionA" value="A" > A
    </label>
    <br>

    <label>
      <input type="checkbox" name="optionB" value="B" > B
    </label>
    <br>

    <label>
      <input type="checkbox" name="optionC" value="C" > C
    </label>
    <br>

    <label>
      <input type="checkbox" name="optionD" value="D" > D
    </label>
    <br>

    <label for="url">URL:</label>
    <input type="text" id="url" name="url" value="xyz.com" readonly>
  </form>

 <script src="script.js"></script>

</body>
</html>

JavaScript File (script.js):

$(document).ready(function() {
    const $checkboxes = $("#checkboxes");
    const integration = [ {all:["push","pull"]},{all:["post","get"]},{all:["put","delete"]}]
    const $eventCheckboxes = $(".integration-event-checkbox");

    // This event handler is not being triggered for dynamically generated checkboxes
    // $(document).on("change", ".integration-event-checkbox", (e) => {
    //     console.warn("Checkbox changed");
    //     console.warn("event",e);
    //     update_url();
    //     e.preventDefault();
    //     e.stopPropagation();
    // });

    const events = display_box(integration[0].all)
    $checkboxes.html(events);

    function display_box(integration){
      const checkboxesHTML = integration.map(item => `
          <label>
              <input type="checkbox" class="integration-event-checkbox" value="${item}" />
              ${item}
          </label>
      `).join('');

          return checkboxesHTML;
    }

    function update_url() {
        const selectedEvents = $eventCheckboxes.filter(":checked").map(function () {
            return this.value;
        }).get().join(",");
        console.log("SELECTED EVENTS: ", selectedEvents);
        // Add the checked events to the URL
        const eventsParam = selectedEvents.length > 0 ? `&events=${selectedEvents}` : '';
        console.log("Events Param: ", eventsParam);

        console.log("event checkboxes: ", $eventCheckboxes);
    }
});

Issue Details:

  1. The $(document).on("change", ".integration-event-checkbox", ...) event handler is not capturing changes for dynamically generated checkboxes.
  2. When attempting to retrieve checked checkboxes using $eventCheckboxes.filter(":checked").map(...), both selectedEvents and the $eventCheckboxes collection are empty.

Steps to Reproduce:

  1. Dynamically generate checkboxes using JavaScript.
  2. Attach a change event using $(document).on("change", ".integration-event-checkbox", ...).
  3. Click on dynamically generated checkboxes and observe the lack of change event triggering.
  4. Attempt to retrieve checked checkboxes using $eventCheckboxes.filter(":checked").map(...) and notice that the result is empty.

Expected Behavior:

The change event should be triggered for dynamically generated checkboxes, and the code should correctly retrieve and display the checked checkboxes.

I attempted to address the issue by reinitializing the $iec variable using let instead of const. I experimented with shifting the code above and below the point of reinitialization, aiming to ensure that the variable captures dynamically generated checkboxes properly.

Expected Behavior:

The change event should be triggered for dynamically generated checkboxes, and the code should correctly retrieve and display the checked checkboxes.

Firebase Auth Issue through React JS and Django Templates

I’m using React JS to create the login page. For the I used Firebase 10.7.1 npm module to create the authentication.

Here is my quick code for Auth:

const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider)
    .then((result) => {
        // Get the ID token directly from the result object
        const idToken = result._tokenResponse.idToken; // Updated this line
        // Send the token to your backend
        sendTokenToBackend(idToken); // Updated this line
    })
    .catch((error) => {
        console.error("Error during Google Sign In: ", error);
    });

Authentication works fine in react JS and when i run the build and paste the files to render them through the django templates. I can see the react code rendered perfectly.

enter image description here

However, now when I try to sign in, halfway of the execution I get the below error doesn’t matter if I allow all domains for CORS in Django:

enter image description here

It had the same behaviour when I was creating the same code in the native Java script for signInWithPopUp. I’ve tried multiple browsers:

  • Chrome, Firefox, Edge

why it does not log anythings in console?

and when three cell matches happens it does not logs anythings and in my eyes it does not logs anythings because when i clicked cell there is no three matches of cells at one click, am i right

const cells = document.querySelectorAll(".cell > img");

const win_combinations = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
];

cells.forEach((cell, index) => {
  cell.addEventListener("click", function () {
    this.src = "Small_uppercase_letter_X.svg.png";

    for (const [a, b, c] of win_combinations) {
      if (
        cells[a].src == "Small_uppercase_letter_X.svg.png" &&
        cells[b].src == "Small_uppercase_letter_X.svg.png" &&
        cells[c].src == "Small_uppercase_letter_X.svg.png"
      ) {
        console.log(cells[a], cells[b], cells[c]);
      }
    }
  });
});

Auto click a Button when script/page loaded

I’m trying to a little script that would click a button when the page is loaded or even better when the script XYZ.js is loaded.

The script I have done works, but only if I add a delay to it. Which is a bit confusing because it normally should also work without adding a delay.

WORKS

window.addEventListener("load", function() {
    setTimeout(function() {
    var button = document.querySelector(".myJS-Button");
        if (button) {
            button.click();
        }
    }, 1);
});

DOESN’T WORK

window.addEventListener("load", function() {
    var button = document.querySelector(".myJS-Button");
    if (button) {
        button.click();
    }
});

How to disable text selection for mobile long press but preserve haptic feedback?

I’m trying to do the opposite of what this post asks. I’m implementing a functionality on my webpage where long pressing an element on mobile triggers a function.

I used long-press-event here. However, long pressing not only triggers the function but also selects some text on the screen. So I added the following CSS to disable text selection.

body {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -webkit-tap-highlight-color: rgba(0,0,0,0);
}

This disabled text selection but also the haptic feedback that comes with it. Is there a way to prevent this, or should I use something like Capacitor to trigger an artificial vibration?

Testing on iOS Chrome.

How to implement map of dynamic indices in dart (or of different execution)

I am working on an app in flutter but I don’t think the solution to this problem is only for dart but all the similar languages (python, js, even java, etc.), so don’t feel frightened to answer if you don’t know “dart”.

What I am trying to do:

  • Map<date, something>

    -> I want to have indexed dates so that I could:

mymap[date0] -> something0

and (most importantly)

mymap.of(index0) -> date0, something0

Problem: I want to have existing gaps so that there don’t have to be entries for every date between for example 14th March and 10th May.

mymap = {
 index 0: date 14.3.2023: something0,
 index 56: date 10.5.2023: something56
}

For that to work as I intend, there is a need for these features:

  • If there is an existing entry date0 and a new date is added that comes before date0:

    -> every other index needs to increase by the difference between date0new and date0old

mymap.add(date 12.3.2023, somethingNew)
-> {
 index 0: date 12.3.2023, somethingNew,
 index 2: date 14.3.2023: something0,
 index 58: date 10.5.2023: something56
}

Any solution can even include two maps, pointer, lists or anything that isn’t too inefficient because I could work around this if I didn’t want my code to work efficient.

Having difficulty saving image to Firebase and then getting image path

I’m working on a blog in React and saving everything in MongoDB. I have an article array with each article having a title, content, author and imagePath.

const articleSchema = mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    content: {
      type: String,
      required: true,
    },
    image: { type: String, required: true },
    author: { type: String, ref: "User", required: true },
    placement: {
      type: String,
      enum: ["featured", "card", "stories"],
      default: "stories",
    },
  },
  {
    timestamps: true,
  }
);

Everything is wrapped up inside a form, including the image so when the user hits the submit button it publishes. When the user publishes the article, the image gets saved to firebase.

const [image, setImage] = useState(null);

const imagePath = uploadBytes(imageRef, image).then((snapshot) => {
    getDownloadURL(snapshot.ref).then((url) => {
      console.log(url);
    });
  });

<Form.Group className="my-2" controlId="content">
  <label>Image</label>
  <input
    type="file"
    placeholder="Image"
    onChange={(e) => setImage(e.target.files[0])}
  ></input>
</Form.Group>

Everything works perfectly fine. The article gets published and the image gets saved to Firebase. When I console.log(imagePath) I get the correct path. When I try saving that to the submitHandler I get an undefined object saved inside my MongoDB instead of the actual image path.

 try {
   const res = await write({
     title,
     content,
     username,
     placement,
     image: toString(imagePath),
   }).unwrap();
   navigate("/");
   toast.success("Article Added!");
 } catch (err) {
   toast.error(err?.data?.message || err.error);
 }
};

MONGODB
_id: 657d70d8af9322a9df1b72be
title: "rhtrth"
content: "rthrth"
image: "[object Undefined]" // imagePath saved as undefined
author: "Dagger"
placement: "featured"

I’m wondering how exactly can I save the image path of my uploaded image inside my MongoDB so when I use loop through the data inside the SingleArticle page:

<img src={article.image} alt="" fill className={styles.image} />

… it will display the proper image.

How to make overflow scroll appear horizontally but make the overflow of the tooltip be visible vertically and horizontally?

How do you make it so that the overflow scroll of this container(horizontally), appears while the vertical overflow is visible as well? On top of that, I would also want the absolutely positioned tooltip/popup to have its overflow to show horizontally.

Basically, I need to:

  • show overflow scroll horizontally
  • show overflow of the popup anywhere(right now it only appears below or above, but not on the left side or right side on top of its parent container)

https://play.tailwindcss.com/Xf3dc6YkLW

Here’s what I’m trying to achieve:
enter image description here

red line being the scrollbar, and the black box, being the tooltip, being able to appear on top of its parent div

PHP Encrypt AES-256-GCM using Phpseclib and Decrypt with Javascript using crypto.subtle

In order to achieve what i wrote as subject, i have this php code:

<?php
require 'vendor/autoload.php';
use phpseclib3CryptAES; // Per l'encryptMessage
use phpseclib3CryptRandom; // Per la generateSharedKey

function generateSharedKey() {
    return base64_encode(Random::string(16));
}
function encryptMessage($messaggio_da_criptare, $chiave) {
    $aes = new AES('gcm');
    $aes->setKey($chiave);
    $iv=base64_encode(openssl_random_pseudo_bytes(12));
    $aes->setNonce($iv);
    $testo_cifrato = $aes->encrypt($messaggio_da_criptare);
    $tag = $aes->getTag();
    $dati_criptati = ['messaggio_criptato_con_tag' => base64_encode($testo_cifrato.$tag),'iv' => $iv];
    return $dati_criptati;
}

$messaggio = "Hello, this is a secret message!";
echo "Messaggio di esempio da criptare: ".$messaggio."<br>";
$chiave = generateSharedKey();
echo "Chiave segreta: ".$chiave."<br>";
$dati_criptati = encryptMessage($messaggio, $chiave);
echo "Messaggio criptato con tag incluso: ".$dati_criptati["messaggio_criptato_con_tag"]."<br>";
echo "IV: ".$dati_criptati["iv"]."<br>";
?>

and this html code

<!DOCTYPE html>
<html>
<script>
var phpkey = "TWw4QCkeZEnXoCDkI1GEHQ==";
var phpiv = "CRKTyQoWdWB2n56f";
var phpmessageencrypted = "7K+HAB7Ch9V4jJ1XJPM0sANXA2ocJok=";

(async () => {
    function _base64ToArrayBuffer(base64) {
        var binary_string = atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }
    async function _importKeyAes(key) {
        return await window.crypto.subtle.importKey("raw",key,{ name: "AES-GCM" },false,["encrypt", "decrypt"]);
    }
    async function decryptMessageSymetric(key, data, iv) {
        var keyArrayBuffer = _base64ToArrayBuffer(key);
        var keyt = await _importKeyAes(keyArrayBuffer);
        var ivt = new TextEncoder().encode(iv);
        var datat = _base64ToArrayBuffer(data);
        var result = await window.crypto.subtle.decrypt({ name: "AES-GCM", iv: ivt, tagLength: 128 },keyt,datat);
        return new TextDecoder().decode(result);
    }
    var result = await decryptMessageSymetric(phpkey, phpmessageencrypted, phpiv); 
    console.log(result);
})();
</script>
</html>type here

The problem is:
If you launch the php script and test the result with an online tool like this:
text
It works and seems that the encryption step is correct.

If you launch the html page and you check with the inspector, with the provided example data it works.

But, if you replace:

var phpkey = "TWw4QCkeZEnXoCDkI1GEHQ=="; var phpiv = "CRKTyQoWdWB2n56f"; var phpmessageencrypted = "7K+HAB7Ch9V4jJ1XJPM0sANXA2ocJok=";

with the php given data, it doesn’t work and browser give the following (and unuseful) error code:
Uncaught (in promise) DOMException: The operation failed for an operation-specific reason
while the online tool report this:

screenshot

I really don’t know what i’m doing wrong. Probably something regarding the KEY and IV, but why they are accepted by the online tool and not by the html/js script?

Thanks for the help.

I’m expecting that it works in a deterministic way.

css toggle with transition effect for expanding div – set max-height to infinity alternative

There is a simple html+css+js code to expand/collapse div with a 1-second effect.

https://jsfiddle.net/zf1rd38y/3/

Css code looks simple:

.smalldesc {
  max-height: 52px;
  overflow: hidden;
  transition: all 1s ease;
  border: 1px solid red;
}

.smalldesc.expand {
  max-height: 150px;
}

The issue is here you see the max-height has a fixed value for .smalldesc.expand (but if the text is long enough, then not all text is displayed when expanded).
If I set max-height: none; instead, then transition: all 1s ease; doesn’t work.

Any ideas how to make it perfectly work for a very long text?

How do I fix undefined property in .php file

I am new to PHP and I’ve encountered an error an error I’m not able to fix. I have an program that giving out an error in VSCode written “undefined property ‘$router'” How do i fix this

$_module OR $_module = CI::$APP->router->fetch_module();
        list($path, $file) = Modules::find($file, $_module, 'config/');

How to endlessly change the src of an image via gsap?

I’m trying to do image swapping via gsap.
I need to do this from image names in an array endlessly.
I do this, but it doesn’t work.
What am I doing wrong?

<div id="communication-img" >
    <img loading="lazy" src="/img/chat.png"/>
  </div>
const images = ['chat1','chat2','chat3']
const img = document.querySelector("#communication-img");     
 gsap
    .timeline({
       scrollTrigger: {
         trigger: img,
         pin: img,
       }
     })
     .to(img, {
       attr:{src:"/assets/img/chat1.png"}
     })