使用输入中的数据更新数组 [英] Update an array with data from inputs

查看:200
本文介绍了使用输入中的数据更新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

示例:

我有一个数组:

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

我做了什么:

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

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

创建两个新输入。

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

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

按下按钮即可添加到数组中。

Pressed button for adding into an array.

什么我正在尝试到达:

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并不困难,谢谢您的建议):

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>

推荐答案


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

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

这篇关于使用输入中的数据更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆