How can I store data from a form to an array in Javascript?

1

Good I would like you to help with this simple form, it is that you can capture 3 numbers from the form, that you can store them in a vector and show them with another show function. I can not make him keep the data, he just repeats it to me. Does anyone have any suggestions to work with this type of data?

<input type="text" id="numero1">
<input type="text" id="numero2">
<input type="text" id="numero3">
<input type="button" value="Capturar" onclick="Capturar()">
<input type="button" value="Mostrar" onclick="Mostrar()">   

savearray = [];
var Capturar = function(){
    var array = [];                                 
    for (var i = 0; i < 3; i++) {               
        array[i] = parseFloat(document.getElementById("numero"+(i+1)).value);
        savearray.push (array[i]);  
        }
    }                       
var Mostrar = function(){
    for (var i = 0; i < savearray.length; i++) {                    
        document.write (savearray[i]);
        }
    }
    
asked by Arifactory 10.04.2018 в 02:42
source

2 answers

1

For this case I see more efficient assigning the same class to all inputs, for when you call it with getElementsByClassName () you will return an array of the inputs, and with it you can save them from your values property.

var Capturar = function(){
        let lstNumero = document.getElementsByClassName("numero"),
            arrayGuardar = [];         
        for (var i = 0; i < lstNumero.length; i++) {    
            arrayGuardar[i] = lstNumero[i].value;
            console.log (lstNumero[i].value);     
            }       
        }
<input type="text" class="numero">
    <input type="text" class="numero">
    <input type="text" class="numero">
    <input type="button" value="Capturar" onclick="Capturar()">
    
answered by 10.04.2018 / 21:59
source
1

You can have a single array and save the numbers on your form. For example:

var array = [];
 for(var i = 0; i < 3; i++){
    array[i] = parseFloat(document.getElementById("numero"+(i+1)).value);
 }

 for(var i = 0; i < array.length; i++){
    console.log(array[i]);//Aquí puedes procesar cada valor del array
 }

The array will have 3 values (in positions 0, 1 and 2), each of them corresponds to each value of the fields number1, number2 and number3 of your form.

    
answered by 10.04.2018 в 03:12