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 = functionalerted(){
    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><inputid="input"><!-- No ending tag --><inputtype = "button"id="button"value="Click me"><!-- No ending tag, move value where it should be --></form><script>var input = document.getElementById("input"); // No .value herevar button = document.getElementById("button");

var myArray = [];

button.onclick = functionalerted (){
    myArray.unshift(input.value); // Moved this line, added the .valuealert(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><inputid="input"type="text"/><buttonid="button"> Click me </button></form><script>var input = document.getElementById("input"); // save the objectvar button = document.getElementById("button");

var myArray = [];




button.onclick = functionalerted (){
    myArray.unshift(input.value); // get the valuealert(myArray);
    returnfalse;
};


</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 = functionalerted (){
  myArray.unshift(i.value);
  alert(myArray);
};​

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