Reputation: 73
I have 8 checkboxes and 1 btn i created with loop JSTL like this
<c:forEach begin="1" end="8" varStatus="loop">
<input type="checkbox" onchange = "x()" id="seat${loop.index}" name="seat${loop.index}" value="seat${loop.index}">
<label for="seat${loop.index}">Seat${loop.index}</label>
</c:forEach>
<input type="submit" value="Save" name="savebtn">
I would like to check if ANY of the checkbox is checked, if none is checked then the button will be disabled
I know how to check if the checkbox is checked, I know how to disable the button. However, I don't know how to implement it with loop, as i haven't worked with JQUERY much before. Here's what i've tried to do.
<script>
function x() {
for (var i = 1; i <= 8; i++){
if ($(seat+i).prop('checked')){
alert("+1")
}
else{
alert("-1")
}
}
}
</script>
This code only check if my first seat is checked and ignored the rest. P.S: the checkboxes have to be initialized with JSTL
Upvotes: 0
Views: 748
Reputation: 20188
You can simply use the following bit of jQuery, which basically comes down to having a selector to get (all) checked checkboxes:
$("input[type=checkbox]:checked").length === 0
If you happen to have other checkboxes in your form, throw in a class:
<input type="checkbox" class="seat" ... />
$("input.seats[type=checkbox]:checked").length === 0
Setting the disabled state of the submit button can be done using:
$("input[type=submit]").prop("disabled", disabled);
where disabled
is a boolean.
Knowing this, you use it to set the submit button disabled state like:
$("input[type=submit]").prop("disabled", $("input[type=checkbox]:checked").length === 0);
Upvotes: 1
Reputation: 803
Your code only check the first seat is checked and ignored the rest, because for checking all checkbox you need to loop through all checkboxes, which you are not doing here.
var count = 0;
$($('input[type="checkbox"]')).click(function(){
if($(this).prop('checked')){
console.log("Checkbox is checked.");
count++;
}
else{
console.log("Checkbox " + index + " is not checked.");
count--;
}
);
//Disable button if no checkbox is checked.
if(count == 0){
$('input[type="submit"]').prop('disabled', true);
}
else{
$('input[type="submit"]').prop('disabled', false);
}
});
Hope this will help you.
Upvotes: 0