lundi 24 juillet 2017

how to target ul li input checkbox items in javascript using .siblings()

i have the following javascript code that works perfectly for most checkboxes, where the script determines if more than 1 checkbox is selected and if so it hides the rest of the checkboxes:

var limit = 1;

    $('input[type="checkbox"]').on('change', function(evt) {
        console.log('checkboxSelectedLimit: detects checkbox');
        if($(this).siblings(':checked').length >= limit) {
            this.checked = false;
            console.log('too many checkboxes selected');
        }
    });

using the following html structure:

<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>

yet when i move my checkboxes into an ordered list like below:

<ul>
<li><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2</li>
<li><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3</li>
<li><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4</li>
<li><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5</li>
<li><input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1</li>
</ul>

my javascript does fire that it is checked, but th .siblings() doesn't seem to be firing as it does not work. i assume i am needing to update this script to target items in an ul li, yet when i change:

$('input[type="checkbox"]').on('change', function(evt)

to

$('ul li input[type="checkbox"]').on('change', function(evt)

it does not work.

any help would be greatly appreciated by someone smarter than myself.




Aucun commentaire:

Enregistrer un commentaire