lundi 30 novembre 2015

Javascript, Determining Which Checkboxes Are Checked

I'm writing up product comparison functionality and it's going rather well, however, I'm having some trouble looping and checking the states of the checkboxes which will determine which products to compare. For example, I may click the compare checkbox on 3 items and then click 'compare selected' and the intention is that all 3 products that are checked will be displayed in a comparison window.

Now, the checkboxes in question are appended dynamically to the page via WordPress and are given a class of 'comparable--object' and a unique identifier using a data attribute.

Here's my HTML

<label>Checkbox</label>
<input class="comparable--object" data="0" type="checkbox">

<label>Checkbox</label>
<input class="comparable--object" data="1" type="checkbox">

<label>Checkbox</label>
<input class="comparable--object" data="2" type="checkbox">

<label>Checkbox</label>
<input class="comparable--object" data="3" type="checkbox">

I'm using this to loop through all the checkboxes on the page.

var checkboxes = document.querySelectorAll('.comparable--object');
    for(var obj = 0; obj < checkboxes.length; obj++) {
        self = checkboxes[obj]; 
        // determine which checkboxes are checked
    }

I tried to effectively assign an event listener to each self object in the loop, however, this would only return the last index for each checkbox i.e. self[maxlength];

I tried using .checked and still nothing... I feel i'm over complicating this...

Thanks for any feedback!




Aucun commentaire:

Enregistrer un commentaire