如何检索输入中的值?

时间:2015-12-12 18:12:58

标签: javascript html arrays html5 var

我正在尝试检索输入中的值,但是我不太清楚如何执行此操作。

这是我的代码:

<body onload="displayMessage()">
  <h1> JavaScript Arrays</h1>
  <br>
  <form name="hey">
    Enter value:
    <br>
    <input type="" name="firstname" value="">
    <br>
    <button type="button" onclick="displayMessage()">Add to list</button>
  </form>

  <p></p>

  <p id="pie"></p>

  <br>

  <p id="beef"></p>

</body>

3 个答案:

答案 0 :(得分:0)

您在+之后错过了"The user entered: "符号,我认为您希望将userInput而不是"Arrays"推送到数组中。

我还使用了.insertAdjacentHTML(),因此您没有覆盖原始的.innerHTML设置。我通过将pie元素存储在变量中来缩短代码。

var Arrays = ["Printer", "Tablet", "Router", "Smart phone", "Motherboard", "Hard drive"];
document.getElementById("beef").innerHTML = Arrays;


function displayMessage() {
  var userInput = document.hey.firstname.value; 
  var pie = document.getElementById("pie");

  // ----------------------------------v
  pie.innerHTML = "The user entered: " + userInput + "<br>";

  Arrays.push(userInput); // <------------ push the new item

  // Prevent overwrite--v
  pie.insertAdjacentHTML("beforeend", Arrays);
}
<h1> JavaScript Arrays</h1>
<br>
<form name="hey">
  Enter value:
  <br>
  <input type="" name="firstname" value="">
  <br>
  <button type="button" onclick="displayMessage()">Add to list</button>
</form>

<p></p>

<p id="pie"></p>

<br>

<p id="beef"></p>

其余的都是正确的。

此外,对于变量名称使用小写单词是个好主意。这是常用的JavaScript约定。

答案 1 :(得分:0)

您没有将userInput添加到数组中,只需添加一个静态文本&#39; Arrays&#39;到数组

function displayMessage() {
  var userInput = document.getElementsByName("firstname")[0].value;
  document.getElementById("pie").innerHTML = "The user entered: " + userInput + "<br>";
  Arrays.push( userInput );
  document.getElementById("pie").innerHTML = Arrays.join( "," );
}

您还错过了+之前的连接运算符userInput

答案 2 :(得分:0)

  • 您需要+ user entered: " + userInput
  • Arrays.push(userInput);
  • document.getElementById("beef").innerHTML = Arrays;
  • userInput && Arrays.push(userInput);以防止空插入

var Arrays = ["Printer", "Tablet", "Router", "Smart phone", "Motherboard", "Hard drive"];
document.getElementById("beef").innerHTML = Arrays;


function displayMessage() {
  var userInput = document.hey.firstname.value;
  userInput && Arrays.push(userInput);
  document.getElementById("pie").innerHTML = ("The user entered: " + userInput + "<br>");
  document.getElementById("beef").innerHTML = Arrays;
}
<body onload="displayMessage()">
  <h1> JavaScript Arrays</h1>
  <form name="hey">
    Enter value: <input type="" name="firstname" value=""> <button type="button" onclick="displayMessage()">Add to list</button>
  </form>
  <p id="pie"></p>
  <p id="beef"></p>