mardi 20 juin 2017

Running a function when there is change in checkboxes generated by JavaScript

I am creating a web page, and populating values in that page based on a CSV file.

Depending on the number of columns in the CSV file, I want to generate a list of checkboxes with those values. I have that working:

function updateKey() {
    var key = '';
    for (var item in data[0])
    {
        key += '<input type="checkbox" name="' + item + '" value="' + item +'"> '
        key += item + "<br>\r\n"
    }
    document.getElementById('key').innerHTML = key
}

Now I want to detect when a user checks these checkboxes, and run functions based on that. For example, let's say I want to only show the rows in the CSV file that are checked. I would need to listen for the checkbox state to change, and then calculate which checkboxes are checked, and then update the HTML accordingly.

I was looking on stackoverflow and found a function like this:

var selected = [];
$('#key input[type="checkbox"]:checked').each(function () {
    selected.push($(this).attr('name'));
});

However, it does not seem to trigger when I check the boxes. I added an alert window right after the push function, and nothing seems to happen. Is it because these check boxes are generated after the page loads? Is there a way to listen to these dynamically created checkboxes?




Aucun commentaire:

Enregistrer un commentaire