Reputation: 21621
I want to know whether at least on checkbox was checked, so I'm using the following code.
function CheckIfAtLeastOneBoxIsCheckedBeforeSavingForm() {
var n = $('input[id*="ckHMreq"]:checked').length;
alert(n);
}
When no checkbox is checked, the alert message box displays 0. However, when at least one checkbox is checked then the alert message box doesn't even display.
Any reason for that?
This is the HTML produced by the browser
<input id="contentMain_cklistPayroll_gvCKList_ckHMreq_0" type="checkbox" name="_ctl0:contentMain:cklistPayroll:gvCKList:_ctl2:ckHMreq" />
I also added "checked" to the jquery code. I still get 0 when no checkbox is checked and no message box when any checkbox is checked.
Upvotes: 1
Views: 889
Reputation: 4761
Your original code always shows the number of checkbox inputs, not 0...
http://jsfiddle.net/hRubC/ (checked) http://jsfiddle.net/szuzv/ (unchecked)
... so there may be flaw in your html.
As suggested in another answer, it does appear you will want to add :checked
to your selector.
EDIT:
http://jsfiddle.net/HFzJw/
At least in Chrome, your original selector works fine with the input
markup you added to your question. Perhaps this is a browser-specific issue?
EDIT 2: http://jsbin.com/iperin/1/edit (jsfiddle seems to be down this morning)
In response to your comment that you are getting the same with all browsers, here is another working example, matching exactly the markup you show in your question. Does this example not work correctly when you try it? If it does work correctly, please examine what else might be different elsewhere on your page.
Upvotes: 1
Reputation: 219930
You should add :checked
to your selector, so that it only selects checked checkboxes:
function CheckIfAtLeastOneBoxIsCheckedBeforeSavingForm() {
var n = $('input[id*="ckHMreq"]:checked').length;
alert(n);
}
Upvotes: 2