The code you've provided will execute immediately upon the page loading. At that point, the form field will be empty, resulting in a value of ''
. When alerted, this empty string will display as a blank alert message due to the default toString
operation on the array.
To ensure that your unshift
code is triggered by a user action, such as clicking a button, you should place it within a function assigned to the onclick
event of the button. In this case, make sure to remove .value
from the initial assignment of input
and include it inside the function where unshift
is called:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
Additionally, some notes to consider:
In HTML, </input>
tags are not necessary and are typically left unclosed. Only close them if you're using XHTML, which requires self-closing tags like <input id="input" />
.
For an input
button, the text displayed on it should go within the value
attribute, rather than between opening and closing tags. If you need to enclose text within tags, use the button
element instead of input
.
Considering these points, here's a simplified version of your code: Live copy | source
<form>
<input id="input"><!-- No ending tag -->
<input type = "button" id="button" value="Click me"><!-- No ending tag, move value where it should be -->
</form>
<script>
var input = document.getElementById("input"); // No .value here
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // Moved this line, added the .value
alert(myArray);
};
</script>