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
}
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($('#my-element').attr('type') == 'radio')
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.
精彩评论