javascript 在按名称或 id 查找后查找表单元素的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5973289/
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
Finding a form element's type after finding it by name or id
提问by alex
Probably a dumb question, but is there a way in JavaScript to find out a form element's type (text, checkbox, etc.) from a form element after finding it by name or id? Either in plain old JavaScript or using jQuery-style syntax or methods would be ideal.
可能是一个愚蠢的问题,但是 JavaScript 中有没有办法在通过名称或 id 找到表单元素后从表单元素中找出表单元素的类型(文本、复选框等)?使用普通的旧 JavaScript 或使用 jQuery 风格的语法或方法都是理想的。
Example:
例子:
<input type="text" name="my_text_input" id="my_text_input"/>
<script>var element = document.getElementById('my_text_input'); // now how to get the element type?</script>
I'm not looking for alternatives, this is exactly what I want to do. I'm making a sort of screen scraper that needs to collect this information.
我不是在寻找替代品,这正是我想要做的。我正在制作一种需要收集这些信息的屏幕抓取工具。
回答by alex
回答by suren
$('#form_id input').each(function() {
console.log($(this).attr('type'));
});
回答by coolguy
$('#my_text_input').attr('type');
Similary you can get any propery....class,title or any
类似地,您可以获得任何属性....class、title 或任何
$('#my_text_input').attr('class');
//retrieves classname
$('#my_text_input').attr('class');
//检索类名
回答by nishant pathak
try this :
试试这个 :
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function submit_form()
{
var len = document.form1.elements.length;
for(var i = 0 ; i< len;i++){
if(document.form1.elements[i].type == "text")
alert(document.form1.elements[i].value);
}
}
</script>
<form name="form1" onsubmit="submit_form();">
First name: <input type="text" name="FirstName" value="Mickey"><br>
First name: <input type="textarea" name="FirstName" value="Mickey"><br>
Second name: <input type="text" name="SecondName" value="Mickey"><br>
Last name: <input type="text" name="LastName" value="Mouse"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>