Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if input type is radio using jquery

Tags:

html

jquery

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 } 
like image 268
Darcy Avatar asked Dec 16 '10 18:12

Darcy


People also ask

How do I know if my input radio is selected?

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.

How do you check if a radio is checked?

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.


1 Answers

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.

like image 185
user113716 Avatar answered Oct 12 '22 05:10

user113716