views:

837

answers:

4

I'd like to find out if an input is a checkbox or not, and the following doesn't work:

$("#myinput").attr('checked') === undefined

Thank you once again!

A: 
$("#myinput").attr('type') == 'checkbox'
chaos
+3  A: 
>>> a=$("#communitymode")[0]
<input id="communitymode" type="checkbox" name="communitymode">
>>> a.type
"checkbox"

Or, more of the style of jQuery:

$("#myinput").attr('type') == 'checkbox'
voyager
Perfectly valid. Not the simplest.
KyleFarris
It saves using jQuery's selector engine, the use of which here is completely inappropriate. The first variant is much the better, since avoids any possibility of jQuery's confused `attr()` function messing anything up.
Tim Down
+8  A: 

You can use the pseudo-selector :checkbox with a call to jQuery's is function:

$('#myinput').is(':checkbox')
Ken Browning
This is the method I always use.
Topher Fangio
You really can't get any simpler than that.
KyleFarris
Why use the selector engine for this? It's completely unnecessary.
Tim Down
@Tim Down I take your point that there might be more efficient ways to accomplish the same thing. I suppose I like this version because the code is very readable.
Ken Browning
A: 

Use this function:

function is_checkbox(selector) {
    var $result = $(selector);
    return $result[0] && $result[0].type === 'checkbox';
};

Or this jquery plugin:

$.fn.is_checkbox = function () { return this.is(':checkbox'); };
Anatoliy