0

I am currently using a catch all method for all inputs on my form when it is being handled by jQuery.

$.each($(':input'),function()
{
    //stuff                 
});

What I need to be able to do is see if any of those inputs is a checkbox, at the moment the only thing I can find is to say if the field is checked or not.

Any help would be greatly appreciated.

2
  • Just for your information: you have picked the wrong answer for two reasons reason a: :input Matches all input, textarea, select and button elements. obviously, select are not needed in here. input would be more correct in this case. reason b: the select all and then filter approach (input -> each -> if type == checkbox ) will cause unnecessary iterations, while input[type=checkbox] will filter them before the .each iteration comes into the picture. Commented Oct 29, 2009 at 6:10
  • Thanks for your concern, however selects are needed and I feel :input is the best way forward for the method as a whole. Checkboxes need to be lumped in with everything else but I need something extra to happen when it is them. The iterations will stay the same. Commented Oct 29, 2009 at 14:40

4 Answers 4

4

If you want to know whether it's a checkbox inside that function:

$(':input').each(function() {
    if (this.type==='checkbox')
        ....
});

(Yeah, you can also say $(this).attr('type')==='checkbox' if you're one of those people who're dead set on using jQuery syntax for everything. But really, what's the point? It's only going to be slower and less readable.)

If you want to find only checkboxes, there's a special filter for that:

$(':checkbox').each(function() {
    ...
});
Sign up to request clarification or add additional context in comments.

Comments

4
$('input[type=checkbox]').each(function(){
   // stuff
});

Or even better

$('input:checkbox').each(function(){
   // stuff
})

see at http://docs.jquery.com/Selectors/checkbox

Comments

3

You can do:

$.each($(":input[type=checkbox]"), function() {
    // stuff
}

2 Comments

What's the point of doing :input here instead of just input?
:input is wrong. since it matches all input, textarea, select and button elements. and select are not needed at all in this case
-1

try this in .each function

if($('#myId').attr('type') == 'checkbox')
alert ('checkbox');

UPDATE

$.fn.tagName = function() {            
    return this.attr("type");          
}                                      
  $(document).ready(function() {       
    alert($('#testElement').tagName());
    });                           

1 Comment

checkbox is not a tagName, it's a type.

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.