The objective is to add another item to the array, and make an array like ["Car", "House" , "Boat"] etc.
What is happening is when i console log, i only have one item in my array and not all the values i submit from form.
This is my form
<form onsubmit="guardarNumeros()">
<p>Please insert the items</p>
<input type="text" id="box">
<input type="submit" value="Submit">
</form>
My js
function guardarNumeros(){
var items = [];
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
}
Thank You !
Your items
array is within the scope of your guardarNumeros
function and will get declared every time guardarNumeros
is called, if you want it to persist it needs to be outside:
var items = [];
function guardarNumeros() {
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
}
As mentioned in the comments a form submission will refresh the page by default, to prevent this you need to return false:
<form onsubmit="return guardarNumeros()">
function guardarNumeros() {
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
return false;
}
http://plnkr.co/edit/mGLCT97QwM8CvD3I5yUp?p=preview
By including the items inside the scope of your functions you were declaring the array every time.
var items = [];
function guardarNumeros() {
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
return false; // stop submission
}
<form onsubmit="return guardarNumeros()">
<p>Please insert the items</p>
<input type="text" id="box">
<input type="submit" value="Submit">
</form>
You have to declare the array outside the function. because whenever you hit the submit button a new array object is being created and the previous one is being lost because of scope.
You know if we declare a variable inside any function this variable is only visible in this function. Outside this function we can't access it. In your case you declare an array inside the function, then push value to it and also log it. But if you try to access this array from outside the function you will get error if you use strict mode.
Just declare the array in global scope, or also you can pass the array as an argument. this will solve your problem..
var items = [];
function guardarNumeros(){
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
}
Or use this. But make sure you declare the array anywhere in parent function where you call the function.
function guardarNumeros(items){
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
}
In this case you also have to check some condition...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With