jQuery 检查输入是文本框、选择、文本区域还是单选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11215598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if input is textbox, select, textarea or radio
提问by Joe
I have a form with different html input fields...
我有一个带有不同 html 输入字段的表单...
1) <input type="text">
2) <textarea></textarea>
3) <input type="checkbox">
4) <input type="radio">
5) <select></select>
How would I be able to determine what type of input field it is using jQuery. For example: If I wanted to do a check to see if input = "select" then do stuff.
我如何能够确定它使用 jQuery 的输入字段的类型。例如:如果我想检查一下 input = "select" 是否可以执行操作。
回答by undefined
$('input') // selects all types of inputs
$('input:checkbox') // selects checkboxes
$('select') // selects select element
$('input:radio') // selects radio inputs
$('input[type="text"]') // selects text inputs
you can use event.target.type
, this alerts what type of input
, textrea
or select
is the target of the event.
您可以使用event.target.type
,这会提醒 什么类型的input
,textrea
或者select
是事件的目标。
$('input, textarea, select').change(function(event){
alert(event.target.type)
})
回答by septemberbrain
回答by Frankey
You can loop through all the form elements using :input
as selector. Since select
and textarea
elements do not have a type
attribute, you want to use .is()
您可以使用:input
as 选择器遍历所有表单元素。由于select
和textarea
元素没有type
属性,因此您要使用.is()
$(':input').each(function(){
if($(this).is('select')){
var inputType = 'select';
}else if($(this).is('input:text')){
var inputType = 'text';
}else if($(this).is('input:checkbox')){
var inputType = 'checkbox';
}
console.log('input type = '+inputType+');
});
回答by Brian Glaz
You can do this by writing a selector that will pull out each of these elements, and then you can iterate through them and check the type. Something like this:
您可以通过编写一个选择器来提取这些元素中的每一个,然后您可以遍历它们并检查类型。像这样的东西:
$('input, textarea, select').each(function() {
var el = $(this);
if(el.is('input')) { //we are dealing with an input
var type = el.attr('type'); //will either be 'text', 'radio', or 'checkbox
} else if(el.is('select')) { //we are dealing with a select
//code here
} else { //we are dealing with a textarea
//code here
}
});
回答by David Cheung
For 1, 3, 4:
对于 1、3、4:
$("input").attr('type');
回答by workoholic
I suggest you use JQuery is syntax
我建议你使用 JQuery is 语法
Something along the lines of
类似的东西
$(document).ready(function() {
var items = $("input");
if(items.first().is("input[type=text]")) {
alert("Text type");
}
});
You can check it out here http://jsfiddle.net/JRLn9/2/
你可以在这里查看 http://jsfiddle.net/JRLn9/2/
回答by Sebastian
var tipo = $('#elemento14').attr('type');