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");
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.
$( ":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.
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.
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.
You should quote the attribute when selecting and include []
:
$("#myform input[name='foo[]']:checked:enabled");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With