Reputation: 1946
I have a bunch of checkboxes, that I'd really like to make the user only able to select upto 5. Once selected 5, then the others are then disabled.
The HTML markup is:
<ul class="options-list">
<li>
<input type="checkbox" value="259" name="bundle_option[9][]" id="bundle-option-9-259" class="change-container-classname checkbox bundle-option-9">
<span class="label"><label for="bundle-option-9-259">1 x Test 1</label></span>
</li>
<li>
<input type="checkbox" value="260" name="bundle_option[9][]" id="bundle-option-9-260" class="change-container-classname checkbox bundle-option-9">
<span class="label"><label for="bundle-option-9-260">1 x Test 1</label></span>
</li>
<li>
<input type="checkbox" value="261" name="bundle_option[9][]" id="bundle-option-9-261" class="change-container-classname checkbox bundle-option-9">
<span class="label"><label for="bundle-option-9-261">1 x Test 1</label></span>
</li>
<li>
<input type="checkbox" value="262" name="bundle_option[9][]" id="bundle-option-9-262" class="change-container-classname checkbox bundle-option-9">
<span class="label"><label for="bundle-option-9-262">1 x Test 1</label></span>
</li>
<li>
<input type="checkbox" value="263" name="bundle_option[9][]" id="bundle-option-9-263" class="change-container-classname checkbox bundle-option-9">
<span class="label"><label for="bundle-option-9-263">1 x Test 1</label></span>
</li>
<li>
<input type="checkbox" value="264" name="bundle_option[9][]" id="bundle-option-9-264" class="change-container-classname checkbox bundle-option-9">
<span class="label"><label for="bundle-option-9-264">1 x Test 1</label></span>
</li>
</ul>
My main problem is targeting the checkboxes.
Can I target them using the name
value of bundle_option[9][]
?
Thanks
Upvotes: 2
Views: 192
Reputation: 337580
Try this:
$(".checkbox").change(function() {
var count = $(".checkbox:checked").length;
if (count >= 5) {
$(".checkbox").not(":checked").prop("disabled", "disabled");
}
else{
$(".checkbox").removeProp("disabled");
}
});
Upvotes: 0
Reputation: 639
You could use the checked selector to grab the selected checkboxes, like,
$("input[name='bundle_option[9][]']:checked")
Upvotes: 0
Reputation: 75317
Yes you can, but because you have [
and ]
's in the name (which have a special meaning in jQuery selectors), you have to escape them with \\
; (taken from API docs);
If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \.
$(':checkbox[name="bundle_option\\[9\\]\\[\\]"]');
See http://jsfiddle.net/G9JCw/
Upvotes: 3