WXR WXR - 1 year ago 65
jQuery Question

Why I can't flip the check property using prop() with a multiple selector?

I know usually when multiple classes are needed to select different classes we use

and I searched around too to make sure I didn't remember wrong but somehow if I use
there's no error but it wouldn't detect the second select only detect the first. If I call the classes separately then the code would work though. Can someone let me know what I have done wrong with the jQuery?

this works.

if(($('.use-remaining').prop("checked")) || (($('.use-briquettes').prop("checked")))){}

but if I do it this way, it wouldn't work

if(($('.use-remaining, .use-briquettes').prop("checked"))){}

I have three checkbox. Only one can be checked before a form submits. When form submits it'll check which checkbox is checked. If either one of the classes from the above code is checked then the form will check for a certain inputs if the 3rd checkbox is checked then it'll check for a different validation.

Just that since those two check boxes have the same inputs to check I figure why not combine them if possible.

Answer Source

Per the jQuery docs:

.prop( propertyName )

Description: Get the value of a property for the first element in the set of matched elements.

And also:

The .prop() method gets the property value for only the first element in the matched set.

With multiple selectors, it only checks the first selected element's property. Consider the following snippet:

$("#test_button").click(function() {
  console.log($("#test, .test_2").prop("checked"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="test">
<input type="checkbox" class="test_2">
<button id="test_button">
Notice that when the first isn't selected but the second is, it still is false!

As you can see, it will be true when the first element is checked or all are and the other isn't, or when they are all checked, but not when the second is checked, and the first isn't.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download