Javascript 确定jQuery中的:输入类型
我正在所有表单元素上运行.each()循环。我找不到确定输入类型的方法(是否为复选框、文本、选择、文本区域等) 有什么想法吗Javascript 确定jQuery中的:输入类型,javascript,jquery,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"));
// 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;
});
小提琴:
我建议:
$("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;
}
});
.
$(this.attr(“type”)
返回什么?那应该很好。您还可以将其简化为这个。键入。如果您没有得到您期望的内容,那么请确保您选择了正确的内容-无论是针对您的单击处理程序还是针对您正在循环的输入。如果是这样的话,获取类型值应该是可行的。@James$(这个)。attr(“type”)
不适用于select
、textarea
和按钮
@brendanbulen-啊,很好这个.tagName
对这种情况会有帮助。@jamesalardice,所以如果我理解正确,没有一个集合函数可以返回表单“input”类型,但如果它是一个输入字段,它是一个复选框、文本等,它也会崩溃?我可以运行多个条件来检查它是否是输入,然后检查属性类型。我将1)通过直接访问此.tagName
来替换$(this).prop(“标记名”)
,以及选择
和文本区域
,哪些没有类型
属性?@DavidThomas jquery就是这样实现的:
$("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;
}
});
$("form[name='test'] :input").each(function() {
alert(this.type);
});