简体   繁体   中英

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 other numbers.

I'm trying to apply method from UncleDave's answer here: JavaScript - Add Value from input box to array

Example:

I have an array:

var exampleArray = [[1, 1.5], [1, 1], [0, 25.5]];

What I have done:

Wrote value 25 in first input. Wrote value 1.5 in the second input.

Create two new inputs.

Wrote value 25.4 in first input. Wrote value 1 in the second input.

Pressed button for adding into an array.

What I am trying to reach:

var exampleArray = [[1, 1.5], [1, 1], [0, 25.5], [25, 1.5], [25.4, 1]];

What I have reached:

"Udefined" in the console log.

Here Is jsfiddle link with my code: https://jsfiddle.net/aectann/k3qwoz0g/12/

updated with snippet (ok, it was not hard at this time, MTCoster, thank you for advice):

 var totalInputs; var myInputs; var tmpARR = []; var count = 0, types = ['t', 'C' /*, 'Q'*/ ], button = document.getElementById('button'); button.addEventListener("click", createInputs, false); function createInputs() { if (!validInput()) { return; } count += 1; createInput(count); } function createInput(count) { totalInputs = document.getElementsByClassName('myInput').length; var existingNode = document.getElementsByClassName('myInput')[totalInputs - 1]; types.forEach(function(type) { var newNode = existingNode.cloneNode(); newNode.value = null; newNode.id = type + +count; newNode.placeholder = 'Placeholder ' + type; newNode.dataset.id = 'id' + count; appendNode(newNode); }) } function appendNode(node) { document.querySelector('#div').appendChild(node); } function validInput() { myInputs = document.getElementsByClassName('myInput'); var valid = true; Array.prototype.slice.call(myInputs).forEach(function(input) { input.classList.remove('error'); if (!input.value) { input.classList.add('error'); valid = false; } }); return valid; } function removeError(event) { event.classList.remove('error'); } function guardarNumeros() { boxvalue = document.getElementsByClassName('myInput').value; tmpARR.push(boxvalue); console.log(tmpARR); return false; } 
 #title { font-family: 'Times New Roman', Times, serif; font-size: 200%; } #step { font-size: 15pt; clear: both; } #step2 { font-size: 15pt; clear: both; } #step3 { font-size: 15pt; clear: both; } summary { background: #009688; color: #fff; padding: 5px; margin-bottom: 3px; text-align: left; cursor: pointer; padding: 5px; width: 250px; /*background-color: #4CAF50;*/ } summary:hover { background: #008999; } .displayBlockInline-Flex { display: inline-flex; } #margin20 { margin-left: 20px; vertical-align: middle; } #container { width: auto; height: auto; margin: 0 auto; display: none; } a.myButton { color: #fff; /* цвет текста */ text-decoration: none; /* убирать подчёркивание у ссылок */ user-select: none; /* убирать выделение текста */ background: rgb(212, 75, 56); /* фон кнопки */ outline: none; /* убирать контур в Mozilla */ text-align: center; cursor: pointer; width: 150px; padding-bottom: 11px; } a.myButton:hover { background: rgb(232, 95, 76); } /* при наведении курсора мышки */ a.myButton:active { background: rgb(152, 15, 0); } /* при нажатии */ .button1 { /* background-color: #fc0; /* Цвет фона слоя */ /* padding: 5px; /* Поля вокруг текста */ float: left; /* Обтекание по правому краю */ width: 450px; /* Ширина слоя */ } .button2 { /* background-color: #c0c0c0; /* Цвет фона слоя */ /* padding: 5px; /* Поля вокруг текста */ width: 650px; /* Ширина слоя */ float: right; /* Обтекание по правому краю */ } .clear { clear: left; /* Отмена обтекания */ } .wrapper { width: 1100px; margin-left: 20px; } /*inputs*/ #div { text-align: center; } .myInput { height: 40px; outline: none; width: auto; border: 1px solid #999; border-radius: 4px; padding: 5px 10px; margin: 5px; display: inline-block; } .myInput.error { border: 1px solid red; } #action { margin: 10px 0; text-align: center; } #button { width: 190px; height: 40px; background: #009688; color: #fff; font-weight: 600; font-size: 13px; border-radius: 4px; border: none; /* text-transform: uppercase;*/ outline: none; cursor: pointer; } #button:hover { background: #008999; } 
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> <center> <input type="text" class="myInput" name="nameAlloy" placeholder="Name"> </center> <div id="div"> <!--<form onsubmit="return guardarNumeros()">--> <div id="action"> <button type="button" id="button">Add more inputs</button> </div> <input type="number" onkeypress="removeError(this)" class="myInput" data-id="id0" name="value[]" placeholder="Enter value 1"> <input type="number" onkeypress="removeError(this)" class="myInput" data-id="id0" name="value[]" placeholder="Enter value 2"> <div id="action"> <input type="submit" id="button" value="Add to array"> </div> <!--</form>--> </div> 

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

try this code

function guardarNumeros() {
    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]);
      } else if (tmpARR[tmpARR.length -1] instanceof Array) {
        tmpARR[tmpARR.length -1].push(element.value);
      } else {
        tmpARR.push([element.value]);
      }
    }
      return false;
    }

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.

function guardarNumeros() {
    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);
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM