jeudi 13 juin 2019

How do I add an onchange attribute to a JavaScript generated checkbox that fires when checked/unchecked?

I have a large json list of people, they just have an id and a name. Below I'm looping through it and it's working fine adding a list of checkboxes.

I have another one similar but with a shorter json list and the code's the same so it's not an issue with the json but the way I'm writing my js code.

I'm doing the below.

Creating checkboxes & labels, for each person in obj.people...

var peopleLen = obj.People.length;
for (var i = 0; i < peopleLen; i++) {
    if (i < obj.People.length) {
        checkbox = null;
        label = null;
        linebreak = null;

        linebreak = document.createElement('br');
        checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.name = "target";
        checkbox.value = obj.People[i].ID;
        checkbox.id = "cbTarget" + i.toString();
        label = document.createElement('label');
        label.id = "lbTarget" + i.toString();
        label.htmlFor = "cbTarget" + i.toString();
        //This is where I believe it's wrong:
        checkbox.onclick = function () {
            toggleTargetList(obj.People[i].ID);
        };
        label.appendChild(document.createTextNode('\u00A0\u00A0' + obj.People[i].Name));

        document.getElementById("divcbTargets").appendChild(checkbox);
        document.getElementById("divcbTargets").appendChild(label);
        //Add a line break:
        document.getElementById("divcbTargets").appendChild(linebreak);
    }
}

The function I'm assigning to it is:

function toggleTargetList(t) {
    alert(t);
}

A simple alert.

When I change:

toggleTargetList(obj.People[i].ID);

To:

toggleTargetList(obj.People[0].ID);

It alerts correctly displaying the first person's id, however when it's [i] it alerts the same value (the first value of the json object's people's id property).

I don't see why this is acting up.




Aucun commentaire:

Enregistrer un commentaire