I am trying to add elements to an array via a form. I am using the unshift() method. The code below doesn’t work and I would like to know why.
<form>
<input id="input"> </input>
<input type = "button" id="button"> Click me </input>
</form>
<script>
var input = document.getElementById("input").value;
var button = document.getElementById("button");
var myArray = [];
myArray.unshift(input);
button.onclick = function alerted (){
alert(myArray);
};
</script>
Your quoted code runs immediately when the page is loaded. The form field won’t have anything in it then, so its value will be
''. When you alert that, the defaulttoStringoperation on the array will result in''and the alert will be blank.You want to run your
unshiftcode in response to a user event, such as the button being clicked, rather than right away. You can do that by settinginputto be the element (remove.valuefrom that line) and then moving your line withunshiftinto the function you’re assigning toonclick, adding the.valuethere:Other notes:
You never write
</input>. Normally you don’t closeinputtags at all. If you’re writing XHTML (you probably aren’t), you’d put the/within the maininputtag like this:<input id="input" />. But again, you’re probably not writing XHTML, just HTML.The value (caption) of an
inputbutton goes in itsvalueattribute, not content within opening and closing tags. (You would use opening and closing tags with thebuttonelement, notinput.)Taking all of that together, here’s a minimalist update: Live copy | source