Darcy
Darcy

Reputation: 5368

how to check if input type is radio using 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
}

Upvotes: 37

Views: 45777

Answers (3)

guest but not last
guest but not last

Reputation: 41

if($('#my-element').attr('type') == 'radio')

Upvotes: 4

Mark Baijens
Mark Baijens

Reputation: 13222

That should work you can try to use filter this way instead

if ($('#myElement').filter(':radio').size() > 0) {
    ....//code here
}
and

if ($('#myElement').filter("input[type='radio']").size() > 0) {
    ....//code here
}

Or

$('#myElement:radio').each(function() {
        ....//code here
});

Udate: Are you also sure that the id is unique in the page? If you want to select more as 1 element you can use a class instead.

Upvotes: 1

user113716
user113716

Reputation: 322462

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.

Upvotes: 61

Related Questions