javascript 为什么我无法获取此文本输入字段的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6270975/
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
Why can't I get the value of this text input field?
提问by JJJollyjim
I have a div, which contains a text input field:
我有一个 div,其中包含一个文本输入字段:
<div id="age" class="fullScreen">
<input type="text" id="age" class="textInput" placeholder="Please enter age..." />
<button type="button" onclick="submitAge()">Submit</button>
</div>
submitAge() looks like this:
submitAge() 看起来像这样:
function submitAge() {
var ageVal = document.getElementById("age").text;
alert(ageVal);
}
But in Google Chrome and Webkit Nightly I see an alert with the text "undefined" (I can't test in any other browsers because the page contains web-sockets).
但是在 Google Chrome 和 Webkit Nightly 中,我看到一个带有“未定义”文本的警报(我无法在任何其他浏览器中进行测试,因为该页面包含网络套接字)。
The chrome developer tools show this:
chrome 开发人员工具显示了这一点:
I assume that the problem is that the input is not in a form, but I don't want it to be in a form because I will be submitting the data via websockets.
我认为问题在于输入不在表单中,但我不希望它在表单中,因为我将通过 websockets 提交数据。
Do I have to put it in a form or is there a better solution?
我必须把它放在一个表格中还是有更好的解决方案?
Thanks.
谢谢。
回答by feathj
You have redefined the id "age". Rename either your div or input and you should be fine.
您已经重新定义了 ID“年龄”。重命名您的 div 或输入,您应该没问题。
回答by NightHawk
Try:
尝试:
function submitAge() {
var ageVal = document.getElementById("age").value;
alert(ageVal);
}
回答by Ibu
var ageVal = document.getElementById('age').value;
alert(ageVal)
Note the .value instead of text
注意 .value 而不是文本
回答by WojtekT
Change:
改变:
var ageVal = document.getElementById("age").text;
to
到
var ageVal = document.getElementById("age").value;
回答by noinstance
Try
尝试
document.getDocumentById("age").value;
回答by Ben Roux
You <div>
has the id of age. This is going to return either the div or an array of HTMLElements. Get a uniqueid of the input and you will be golden
你<div>
有年龄的id。这将返回 div 或 HTMLElements 数组。获取输入的唯一id,您将成为黄金