javascript 如何使用javascript获取没有id和name字段的输入框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12913994/
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
how to get value of input box without id and name field using javascript
提问by vishalg
I have a form with 3 input box and all the input box does not have id, name field in it. So if i enter value in it, How can i check the value of input box without id and name field using javascript
我有一个带有 3 个输入框的表单,所有输入框都没有 id、name 字段。因此,如果我在其中输入值,如何使用 javascript 检查没有 id 和 name 字段的输入框的值
<form id='a' action='' >
<input type='text' value='' />
<input type='text' value='' />
</form>
This is the code in html and i want to have the value of input box using javascript. Can i do that?
这是html中的代码,我想使用javascript获得输入框的值。我可以吗?
采纳答案by alex
You could get a reference to them and check their value
property.
你可以得到他们的参考并检查他们的value
财产。
For the luxury of supporting newer browsers...
对于支持较新浏览器的奢侈...
[].forEach.call(document.querySelectorAll("#a input[type='text']"),
function(input) {
var value = input.value;
});
If you need to support the annoying browsers that still seem to linger, just write a bit more code and you're good as gold.
如果你需要支持那些似乎仍然存在的烦人的浏览器,只需多写一点代码,你就会像金子一样好。
var inputs = document.getElementById("a").getElementsByTagName("input");
var i;
var length;
var value;
for (i = 0, length = inputs.length; i < length; i++) {
// Check we have [type='text']
if (inputs[i].type != "text") {
continue;
}
value = inputs[i].value;
}
回答by Josh Lee
回答by Cybear
It looks like you want to do form validation. For form validation in HTML5, check this resource out: http://www.the-art-of-web.com/html/html5-form-validation/
看起来您想要进行表单验证。对于 HTML5 中的表单验证,请查看此资源:http: //www.the-art-of-web.com/html/html5-form-validation/
Basically, you will be able to get by with some validations just by using HTML attributes, and without using JavaScript.
基本上,您只需使用 HTML 属性即可完成一些验证,而无需使用 JavaScript。
回答by Erfan
you can get values by getElementsByTagName
and code would be like this
您可以通过以下方式获取值getElementsByTagName
,代码将是这样的
var inputs = document.getElementsByTagName('input');
value1 = inputs[0].value;
value2 = inputs[1].value;
回答by Tahir Akram
var inpObj = document.getElementsByTagName('input');
for(var i in inpObj){
if(inpObj[i].type == "text"){
alert(inpObj[i].value);
}
}
This code will alert all the input textfields.
此代码将提醒所有输入文本字段。