Ronald bergurman 3rd Ronald bergurman 3rd - 2 months ago 6
HTML Question

How to retrieve the value in the input?

I'm trying to retrieve the value in the input, however I'm not too sure how to do this.

Here is my code:

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



Answer

You're missing the + sign after "The user entered: ", and I assume you want to push userInput instead of "Arrays" into the array.

I also used .insertAdjacentHTML() so that you didn't overwrite the original .innerHTML setting. I shortened the code as well by storing the pie element in a variable.

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>

The rest was correct.


In addition though, It's a good idea to use lowercase words for variable names. This is the common JavaScript convention used.