Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: selecting checked checkbox

Suppose I have the following HTML:

<form id="myform">   <input type='checkbox' name='foo[]'/> Check 1<br/>   <input type='checkbox' name='foo[]' checked='true'/> Check 2<br/>   <input type='checkbox' name='foo[]'/> Check 3<br/> </form> 

Now, how do I select the checked input fields with name 'foo[]'?

This is my attempt, but it doesn't work:

$("#myform input[name='foo']:checked:enabled"); 
like image 439
bart Avatar asked Apr 14 '09 13:04

bart


People also ask

How do you find which checkboxes are checked?

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.

How do I select a check box using type selector?

$( ":checkbox" ) is equivalent to $( "[type=checkbox]" ) . As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied.

Is checked function in jQuery?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.


2 Answers

The name of the field isn't foo, it is foo[]. You could use the attributeStartsWith selector:

$("input[name^='foo']:checked:enabled",'#myform'); 

Ideally, you'd be able to do this:

$("input[name='foo[]']:checked:enabled",'#myform'); 

But as this answer explains, jQuery uses this to parse the value part of the attr=value condition:

(['"]*)(.*?)\3|)\s*\] 

\3 being the group containing the opening quotes, which weirdly are allowed to be multiple opening quotes, or no opening quotes at all. The .*? then can parse any character, including quotes until it hits the first ‘]’ character, ending the match. There is no provision for backslash-escaping CSS special characters, so you can't match an arbitrary string value in jQuery.

In other words, as soon as jQuery hits the first ] it thinks the value is over. So you are stuck with startsWith or using pure DOM elements, as that answer also explains.

SUPER DUPER IMPORTANT EDIT:
This bug is fixed, apparently. You should be able to use the code I described as "ideal", above.

like image 181
Paolo Bergantino Avatar answered Sep 28 '22 05:09

Paolo Bergantino


You should quote the attribute when selecting and include []:

$("#myform input[name='foo[]']:checked:enabled"); 
like image 41
Seb Avatar answered Sep 28 '22 05:09

Seb