mauzilla
mauzilla

Reputation: 3592

Determining the :input type in jQuery

I'm running an .each() loop on all my form elements. I cannot find a way to determine the input type (whether it's a checkbox, text, select, textarea etc...).

Any ideas?

 // When submitting
$("input[name='event_form_submit']").click(function() {
    $("form[name='tepg_form_processor'] :input").each(function() {
        console.log($(this).attr("type"));
       // Determine whether this is a select, input etc?
    });
    return false;
});

Upvotes: 2

Views: 173

Answers (3)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

Try this (jsfiddle):

$("form[name='test'] :input").each(function() {
    alert(this.type);
});

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

I'd suggest:

$("form[name='test'] :input").each(function() {
    /* gets the type of the element ('checkbox','text','radio', etc
       if there's no 'type' then it retrieves the tagName of the
       element instead 'select','textarea', etc */
    var inputType = this.type || this.tagName.toLowerCase();
    console.log(inputType);
    /* then does uses a switch to do something depending
       on what you want to do */
    switch (inputType) {
        case 'text':
            // do something with text-inputs
            break;
        case 'radio':
            // do something with radio-inputs
            break;
        case 'select':
            // do something with select-elements
            break;
        // ...etc...
        default:
            // do something with other elements, element-types
            break;
    }
});

JS Fiddle demo.

Upvotes: 1

Samuel Liew
Samuel Liew

Reputation: 79022

$("form[name='test'] :input").each(function() {
    if(this.tagName == "INPUT") {
        console.log(this.tagName + ": " + this.type);
    }
    else 
        console.log(this.tagName);
});

Fiddle: http://jsfiddle.net/samliew/YSsvp/8/

Available Input Element Types

Upvotes: 2

Related Questions