Reputation: 163
I have a total of ten checkboxes on my page, the last five of them are special. And if anyone of them are checked a want to show a message on the page that extra costs will apply to those products. They all have different name and value. Since I can't have the same id on all the checkboxes I am really stuck.
This was the last thing I tested but I cant get to work for all 5 checkboxes.
var check;
$("#test-with-is").on("click", function(){
check = $("#mycheckbox").is(":checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Any clue what I am doing wrong?
Upvotes: 1
Views: 2413
Reputation: 1
Try using :gt()
selector, which is 0-based indexed, with parameter 4
, change
event
$("input:gt(4)").on("change", function() {
if ($(this).is(":checked")) alert("extra costs will apply");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<label>1<input type="checkbox"></label>
<label>2<input type="checkbox"></label>
<label>3<input type="checkbox"></label>
<label>4<input type="checkbox"></label>
<label>5<input type="checkbox"></label>
<label>6<input type="checkbox"></label>
<label>7<input type="checkbox"></label>
<label>8<input type="checkbox"></label>
<label>9<input type="checkbox"></label>
<label>10<input type="checkbox"></label>
Upvotes: 1
Reputation: 4052
Add a class to your special checkbox, and check by it's property "checked".
$(".special").on("click", function(){
if($(this).prop('checked')){
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="special">
<input type="checkbox" class="special">
<input type="checkbox" class="special">
<input type="checkbox" class="special">
<input type="checkbox" class="special">
Upvotes: 4
Reputation: 44740
add a class to your special checkboxes
class='special_checkbox'
now you can check if anyone of them is checked or not like this
if($('.special_checkbox:checked').length() > 0){
// checked
}
Upvotes: 0
Reputation: 318342
Use a common class
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" class="last_five" />
<input type="checkbox" class="last_five" />
<input type="checkbox" class="last_five" />
<input type="checkbox" class="last_five" />
and check if any of them are checked
$("#test-with-is").on("click", function(){
if ( $(".last_five").is(":checked") ) { // true if any are checked
// do stuff
}
});
Upvotes: 2