Skip to content Skip to sidebar Skip to footer

Update An Array With Data From Inputs

I have several inputs, which I am copying n times and I am trying to add numeric values from inputs in the array. I marked word 'add' because an array may be already filled by othe

Solution 1:

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

You can iterate over the collections for all the numeric inputs and update your result. But I would suggest is to create another class for numeric inputs, so you wouldn't need to check for the type of the input and would keep your code generic.

You can try this code and feel free to clear your doubts in the comments.

functionguardarNumeros() {
    boxvalue = document.getElementsByClassName('myInput');
    i = 0;
    while (i < boxvalue.length) {
        if (boxvalue[i].type == "number") {
            if (boxvalue[i+1] && boxvalue[i+1].type == "number") {
                tmp = [boxvalue[i].value, boxvalue[i+1].value]
                tmpARR.push(tmp);
                i+=2;
            }
        } else {
            i++;
        }
    }
    console.log(tmpARR);
    returnfalse;
}

Solution 2:

The error is in "guardarNumeros" function because getElementsByClassName returns a collection and collection does not have a "value" property.

try this code

functionguardarNumeros() {
    const inputs = [...document.getElementsByClassName('myInput')];
    const inputNumberArr = inputs.filter(x => x.type === 'number');
    // tmpARR = [];for (let i = 0; i < inputNumberArr.length; i++) {
      const element = inputNumberArr[i];
      if (i % 2 === 0) {
        tmpARR.push([element.value]);
      } elseif (tmpARR[tmpARR.length -1] instanceofArray) {
        tmpARR[tmpARR.length -1].push(element.value);
      } else {
        tmpARR.push([element.value]);
      }
    }
      returnfalse;
    }

Post a Comment for "Update An Array With Data From Inputs"