Neil Kelsey Neil Kelsey - 19 days ago 7
jQuery Question

jQuery not working inside of additional tags

I'm trying to 'aim' my JavaScript code towards a particular piece of code and I'm almost there but fallen down at the last hurdle!

I've created a fiddle of what I'm trying to create here;

http://jsfiddle.net/k4mLb14n/1/

<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<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>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>

<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<label><input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1</label><br>
<label><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2</label><br>
<label><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3</label><br>
<label><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4</label><br>
<label><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5</label><br>
<label><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6</label><br>
<label><input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7</label><br>
</div>


So basically I want to create a checklist and limit the amount of items that you can select, in my fiddle I've got the first list exactly how I want it - you can only select 3 items but in the second list you can select as many as you want.

The only difference is that the second list is check boxes are in
<label>
tags which is how I want to structure the code but this breaks my javascript.

So I want to adjust my javascript here so that it works for the second list;

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});


Any advice welcome!

Answer

One option is using the closest method:

if ($(this).closest('.pricing-levels-3').find(':checked').length > limit) {
   this.checked = false;
}

http://jsfiddle.net/k4mLb14n/2/