最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why can't I get the value of this text input field? - Stack Overflow

programmeradmin0浏览0评论

I have a div, which contains a text input field:

<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:

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).

The chrome developer tools show this:

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.

Do I have to put it in a form or is there a better solution?

Thanks.

I have a div, which contains a text input field:

<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:

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).

The chrome developer tools show this:

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.

Do I have to put it in a form or is there a better solution?

Thanks.

Share Improve this question asked Jun 7, 2011 at 20:06 JJJollyjimJJJollyjim 6,21719 gold badges58 silver badges79 bronze badges 2
  • You have 2 HTML elements with ID = age – Ben Roux Commented Jun 7, 2011 at 20:11
  • 1 Not going to post yet another answer because between all the other answers you have your two problems, but #1 you can't have more than one element with the same ID, the behavior is undefined. #2 you need value not text – David Ly Commented Jun 7, 2011 at 20:13
Add a comment  | 

6 Answers 6

Reset to default 7

You have redefined the id "age". Rename either your div or input and you should be fine.

Try:

function submitAge() {
  var ageVal = document.getElementById("age").value;
  alert(ageVal);
}
var ageVal = document.getElementById('age').value;

alert(ageVal)

Note the .value instead of text

Change:

 var ageVal = document.getElementById("age").text;

to

 var ageVal = document.getElementById("age").value;

You <div> has the id of age. This is going to return either the div or an array of HTMLElements. Get a unique id of the input and you will be golden

Try

document.getDocumentById("age").value;
发布评论

评论列表(0)

  1. 暂无评论