确定jQuery中的输入类型

问题描述:

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

任何想法?

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

什么'$(本).attr( “类型”)'返回?这应该没问题。你也可以简化为'this.type'。 –

+0

如果你没有得到你所期望的,那么确保你选择了正确的东西 - 无论是为你的点击处理程序还是你正在循环的输入。如果是的话,获取类型值应该可以工作。 – 2013-02-04 10:08:09

+0

@James'$(this).attr(“type”)''对'select','textarea'和'button'不起作用 –

Try this (jsfiddle):

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

那么'select'和'textarea'没有'type'属性呢? –

+0

运行小提琴,看到神奇:) –

+0

这似乎工作,但我不知道为什么。 –

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

+0

我会1)通过直接访问'this.tagName'替换'$(this).prop(“tagName”)'2)[删除任何链接到w3schools](http://w3fools.com/)。 –

我建议:

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