确定jQuery中的:input类型

时间:2013-02-04 10:04:47

标签: javascript jquery

我在所有表单元素上运行.each()循环。我找不到确定输入类型的方法(无论是复选框,文本,选择,文本区域等)。

有什么想法吗?

 // 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;
});

3 个答案:

答案 0 :(得分:2)

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

小提琴:http://jsfiddle.net/samliew/YSsvp/8/

Available Input Element Types

答案 1 :(得分:1)

我建议:

$("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

答案 2 :(得分:0)

Try this (jsfiddle):

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