lundi 20 novembre 2023

Checkbox value not being returned on checkbox change [duplicate]

I am creating checkboxes from an array of objects. on change, I am not getting back anything.

My code:

let res = [
  { id: "123", fullName: "harry potter", username: "harrypotter" },
  { id: "345", fullName: "hermione granger", username: "hermionegranger" },
  { id: "678", fullName: "ron weasley", username: "ronweasley" },
  { id: "789", fullName: "ginny weasley", username: "ginnyweasley" },
  { id: "987", fullName: "luna lovegood", username: "lunalovegood" },
];

let cbs = document.getElementById("cboxes");
for (const cb of res) {
        cbs.innerHTML += `<div class="form-check form-check-inline">
        <input type="checkbox" class="form-check-input" id="${cb.username}" name="${cb.username}" value="${cb.id}">
        <label class="form-check-label" for="${cb.username}">${cb.username}</label>
        </div>`;
        
let chck = document.getElementById(cb.username);
chck.addEventListener("change", function(event) {
   if (event.currentTarget.checked) {
       alert(`checked ${this.value}`);
   } else {
       alert("not checked");
   }
 });
}
<div id="cboxes"></div>

On checkbox check I want the checkbox value returned. My code is returning nothing.




Aucun commentaire:

Enregistrer un commentaire