If I have some radio buttons:
<input type="radio" name="test" value="apple"> Apple<br/>
<input type="radio" name="test" value="banana" CHECKED> Banana<br/>
<input type="radio" name="test" value="carrot"> Carrot<br/>
and I then define the radio group in jQuery with
var test = $('input:radio[name="test"]')
How can I get the value of the checked element based on the variable test without re-writing
var test_val = $('input:radio[name="test"]:checked').val();
I've tried both
$(test):checked.val();
test:checked.val();
And as part of a change function I've also tried this:
$(test).change(function() {
if ($(this):checked.val() == 'no') {
$('#featured').stop().fadeOut();
} else if ($(this):checked.val() == 'yes') {
$('#featured').stop().fadeIn();
}
});
Just wondering if this is possible or if I have to re-write out the full input selector to get the value.
P.S.
If IE8 doesn't support the :checked
selector, what can I use instead?
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.
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);
Method 2: Using the attr method: It is similar to the above method and more suitable for older jQuery versions. The input can be accessed and its property can be set by using the attr method. We have to manipulate the 'checked' property and set it to true or false depending on whether we want to check or uncheck it.
You can use .filter()
help:
test.filter('input:checked')
.filter()
does also support a callback:
test.filter(function() {
return this.name === 'test' && this.checked
});
I wasn't aware that the :checked
selector does not work with IE8. If that is true, the latter example should work (accessing the node expando directly)
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