如何在JavaScript中将用户输入保存到变量中?

时间:2015-12-06 04:47:50

标签: javascript jquery html5

给出以下HTML:

<div id= "playerNames" class="playerInfo">
            <form name="form1" method="post" action="http://examples.funwebdev.com/process.php" id="newGame">
                <p id= "userInput">
                    <label>Player 1 name: </label></br><input type="text" name="p1" id="nameOne" value="" required></input></br>
                    <label>Player 2 name: </label></br><input type="text" name="p2" id="nameTwo" required></input> <input id="submit" type="submit" value="New Game"/>
                </p>
            </form>
        </div>

以下javascript:

 $(document).ready(function () {
    console.log("jQuery is ready to use...");
    $("#newGame").on("submit", newGameListener);
});

function setUpUsers(){
    var player_One = document.getElementById("nameOne").value;
    var player_Two = document.getElementById("nameTwo").value;
    document.getElementById("pTurns").innerHTML = (+nameTwo+ ", its your turn");
    document.getElementById("pScores").innerHTML = (+nameOne+ ": 50pts </br>" (+nameTwo+ ": 50pts </br>"
}

function newGameListener(e) {
    e.preventDefault();
    setUpUsers();
}

我试图在p元素中附加这两个变量(nameOne,nameTwo)。但是,当运行此代码时,我得到NaN(非数字)而不是用户输入字符串。不确定我应该如何实现这个目标!

2 个答案:

答案 0 :(得分:3)

那是因为您正在将DOM元素转换为数字。结果将是,em ..,NaN。你想要的是元素的价值。您可以通过阅读.value属性来获取值。

document.getElementById("pTurns").innerHTML = (+nameTwo.value + ", its your turn");

但是,由于您希望将值与字符串连接起来,因此无需使用+运算符。

另请注意,不应该依赖全局变量(某些浏览器,如Chrome创建引用具有相应ID的元素的全局变量)来访问元素,它很脆弱,可能会失败。是的,it has been standardized by HTML5,但在我看来,这是一个糟糕的练习。使用document.getElementById方法按ID选择元素。

答案 1 :(得分:1)

由于@Vohuman和@ guest271314回答了您的问题(NaN),但您的HTML和javascript中有几个语法错误,但我修复了我优化了您的javascript。

Jsfiddle

$(document).ready(function() {
  console.log("jQuery is ready to use...");
  $("#newGame").submit(function(e) {
    e.preventDefault();
    var player_One = $('#nameOne').val();
    var player_Two = $('#nameTwo').val();
    $('#pTurns').html(player_One + ", its your turn");
    $('#pScores').html(player_One + ": 50pts </br>" + player_Two + ": 50pts </br>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="playerNames" class="playerInfo">
  <form name="form1" method="post" id="newGame">
    <p id="userInput">
      <label>Player 1 name:</label>
      <br />
      <input type="text" name="p1" id="nameOne" value="" required />
      <br />
      <label>Player 2 name:</label>
      <br />
      <input type="text" name="p2" id="nameTwo" required />
      <input id="submit" type="submit" value="New Game" />
    </p>
  </form>
</div>

<p id="pTurns"></p>
<p id="pScores"></p>