Skip to content Skip to sidebar Skip to footer

Add Form Input To Array With Javascript Using Unshift()

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.

Solution 1:

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 default toString operation on the array will result in '' and the alert will be blank.

You want to run your unshift code in response to a user event, such as the button being clicked, rather than right away. You can do that by setting input to be the element (remove .value from that line) and then moving your line with unshift into the function you're assigning to onclick, adding the .value there:

button.onclick = function alerted (){
    myArray.unshift(input.value);
    alert(myArray);
};

Other notes:

  1. You never write </input>. Normally you don't close input tags at all. If you're writing XHTML (you probably aren't), you'd put the / within the main input tag like this: <input id="input" />. But again, you're probably not writing XHTML, just HTML.

  2. The value (caption) of an input button goes in its value attribute, not content within opening and closing tags. (You would use opening and closing tags with the button element, not input.)

Taking all of that together, here's a minimalist update: 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>

Solution 2:

DEMO

You need to a) get the value in the click and b) return false if you want the button to not submit. I changed to button. Alternative is <input type="button" value="click me" id="button" />

You may even want to empty and focus the field on click...

<form>
<input id="input" type="text"/>
<button id="button"> Click me </button>
</form>


<script>

var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");

var myArray = [];




button.onclick = function alerted (){
    myArray.unshift(input.value); // get the value
    alert(myArray);
    return false;
};


</script>

Solution 3:

You're not getting the new value in the onclick function.

Try this: http://jsfiddle.net/SeqWN/4/

var button = document.getElementById("button");
var i = document.getElementById("input");
var myArray = [];

button.onclick = function alerted (){
  myArray.unshift(i.value);
  alert(myArray);
};​

Post a Comment for "Add Form Input To Array With Javascript Using Unshift()"