PsYcHoSiD
PsYcHoSiD

Reputation: 81

Appending an array from user input in Javascript

Hey guys I’m pretty new to JavaScript. Long story short is I’m starting a web dev boot camp next week so I can have a career change after the new year. I totally get HTML and CSS, and I’ve done a bit of swift. Anyway Arrays are kind of “that thing” that gets to me, so I thought I would challenge myself by just giving little tasks and seeing if I could do it. This one was appending an array from user input, then displaying it. I’ve been working on it for a while and searched through sample code and other forums and am at a loss. Now I am using a basic text editor as I do these at work during “down time” if you catch my drift so maybe it’s a typo that fresh eyes may catch.

Anyway much appreciate any advice.

<!doctype html>
 <html>
<head>


<meta charset="utf-8" />
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>


  <body>

  <input id="names" />
 <button id="nameSubmit">Please Enter A Name</button>
<p id="output"></p>


  <script>


  document.getElementById("nameSubmit").onclick = function(); {

 var nameArray = ["Sean", "Ryan", "Amanda"];
 var name = document.getElementById("names").value;

      nameArray.push("name");
       nameArray.ToString();
       document.getElementById("output").innerhtml = nameArray;

  }



   </script>

   </body>

      </html>

Upvotes: 1

Views: 146

Answers (1)

epascarello
epascarello

Reputation: 207501

You have some basic mistakes

nameArray.push("name");  //You are pushing the string name, not the variable
nameArray.ToString();    //Does nothing
document.getElementById("output").innerhtml = nameArray;  //there is no innerhtml, case matters.

Should be

nameArray.push(name);  
document.getElementById("output").innerHTML = nameArray.join(",");  

Now the issue will have is you declare the array inside of the click so it will always reset. If you do not want it to reset, you would need to move it outside.


var nameArray = ["Sean", "Ryan", "Amanda"];
document.getElementById("nameSubmit").onclick = function() {

  var name = document.getElementById("names").value;
  nameArray.push(name);
  document.getElementById("output").innerHTML = nameArray.join(",");

};
<input id="names" />
<button id="nameSubmit">Please Enter A Name</button>
<p id="output"></p>

Upvotes: 2

Related Questions