Shanka
Shanka

Reputation: 821

jQuery - Check if a group of Check Boxes are checked

How do I check if any of the Check Boxes in chkInv* (chkInv1 and chkInv2) are checked and exclude chkUnrelated.

<label for="chkInv2-0">
  <input name="chkInv2" id="chkInv2-0" type="checkbox" value="1">
  chkInv2
</label>

<label for="chkInv2-1">
  <input name="chkInv2" id="chkInv2-1" type="checkbox" value="2">
  chkInv2
</label>

<label for="chkInv3-0">
  <input name="chkInv3" id="chkInv3-0" type="checkbox" value="3">
  chkInv3
</label>

<label for="chkInv3-1">
  <input name="chkInv3" id="chkInv3-1" type="checkbox" value="4">
  chkInv3
</label>

<label for="chkUnrelated">
  <input name="chkUnrelated" id="chkUnrelated-1" type="checkbox" value="4">
  chkUnrelated
</label>

My current code checks all the Check Boxes of the page.

var checkBoxes = $('input:checkbox:checked').length;

Can I use some kind of regular expression?

var checkBoxes = $('input:checkbox[name=chkInv*]:checked').length;

Upvotes: 0

Views: 2536

Answers (2)

Manish Jangir
Manish Jangir

Reputation: 5437

To check any of the checkbox is checked, use the following

if($('input[name^="chkInv"]:checked').length > 0) {
           //Code goes here
}

This will automatically exclude the checkbox with name chkUnrelated

Upvotes: 1

Hemal
Hemal

Reputation: 3760

This will give you checkboxes without chkUnrelated

var checkBoxes = $(':checkbox[name^=chkInv]');

Upvotes: 0

Related Questions