Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.

function isCheckedById(id) {     alert(id);     var checked = $("input[@id=" + id + "]:checked").length;     alert(checked);      if (checked == 0) {         return false;     } else {         return true;     } } 
like image 328
Jake Avatar asked Feb 05 '10 00:02

Jake


People also ask

How do you check if a checkbox is checked using jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How do you check if checkbox is checked or not?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Which method of checkbox view is used to check if the checkbox option is ticked?

Checking if a checkbox is checked by using is The is method of jQuery provides us a way to match one or multiple elements against a given selector, jQuery object, or element. It returns true if at least one element matches.


2 Answers

$('#' + id).is(":checked") 

That gets if the checkbox is checked.

For an array of checkboxes with the same name you can get the list of checked ones by:

var $boxes = $('input[name=thename]:checked'); 

Then to loop through them and see what's checked you can do:

$boxes.each(function(){     // Do stuff here with this }); 

To find how many are checked you can do:

$boxes.length; 
like image 69
John Boker Avatar answered Sep 19 '22 04:09

John Boker


IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" /> <input type="checkbox" name="chk[]" id="chk[]" value="Bananas" /> 

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">     <input type="checkbox" name="chk[]" value="Apples" />      <input type="checkbox" name="chk[]" value="Bananas" /> </fieldset> 

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0; //there should be no space between identifier and selector  // or, without the container:  var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0; 
like image 44
nickf Avatar answered Sep 17 '22 04:09

nickf