繁体   English   中英

使用输入中的数据更新数组

[英]Update an array with data from inputs

我有几个输入,我正在复制n次,并且试图从数组中的输入中添加数值。 我将单词标记为“添加”,因为数组可能已经被其他数字填充。

我正在尝试从UncleDave的答案中应用方法: JavaScript-从输入框向数组添加值

例:

我有一个数组:

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

我做了什么:

在第一个输入中写入值25。 在第二个输入中写入值1.5。

创建两个新输入。

在第一个输入中写入值25.4。 在第二个输入中写入值1。

按下按钮以添加到阵列中。

我想达到的目标:

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

我已经达到的目标:

控制台日志中的“ Udefined”。

这是带有我的代码的jsfiddle链接: https ://jsfiddle.net/aectann/k3qwoz0g/12/

更新了代码段(好的,MTCoster现在还不难,谢谢您的建议):

 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> 

该错误在“ guardarNumeros”函数中,因为getElementsByClassName返回一个集合,并且集合没有“ value”属性。

试试这个代码

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;
    }

getElementsByClassName()方法以NodeList对象的形式返回文档中具有指定类名的所有元素的集合。

您可以遍历所有数字输入的集合并更新结果。 但是我建议为数字输入创建另一个类,这样就不需要检查输入的类型,并且可以使代码通用。

您可以尝试使用此代码,并随时清除注释中的疑问。

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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