37

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
}
1
  • 1
    if you solved your own problem you should have posted it as an answer and chosen it. Commented Dec 16, 2010 at 18:26

3 Answers 3

62

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately is(':radio') returns true for a checkbox as well as a radio button, so might be best to .attr('type') =='radio' instead.
4
if($('#my-element').attr('type') == 'radio')

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.