I want to handle html elements differently based on their type.
Using jquery, how do I check to see if an input type is a radio button?
I've tried:
if ($('#myElement').is(':radio')) { ....//code here }
and
if ($('#myElement').is("input[type='radio']")) { ....//code here }
Neither of these worked. Any ideas?
EDIT:
if ($('#myElement').is(':radio')) { ....//code here }
works, but my radio buttons don't have the id attribute, they only have a name attribute, which is why it did not work.
I changed my code to:
if ($('input[name=' + myElement + ']').is(":radio")) { ....//code here }
Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.
To find the selected radio button, you follow these steps: Select all radio buttons by using a DOM method such as querySelectorAll() method. Get the checked property of the radio button. If the checked property is true , the radio button is checked; otherwise, it is unchecked.
That should work as long as the elements are loaded.
// Ensure the DOM is ready $(function() { if ($('#myElement').is(':radio')) { //code here } });
If you're assigning handlers based on type, another approach would be to use .filter()
.
$(function() { var el = $('#myElement'); el.filter(':radio').change(function() { //code here }); el.filter(':checkbox').change(function() { // other code here }); });
If it doesn't pass the filter()
, the handler won't be assigned.
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