简体   繁体   English

将输入中的值推入数组中的某些位置

[英]Push values from inputs in certain positions in an array

In continuation to Update an array with data from inputs . 继续使用输入的数据更新数组

Now I must put values into tmpARR array like: 现在,我必须将值放入tmpARR数组,例如:

var count = 0;
var tmpARR = ["count++", "text value from text input", "value from input Num 1", "0", "value from input Num 2", "Just some default text"];

The question is: how should I change guardarNumeros() for adding information in an array like: 问题是:我应该如何更改guardarNumeros()以便在数组中添加信息,例如:

var tmpARR = ["count++", "text value from text input", "value from input Num 1", "0", "value from input Num 2", "Just some default text"];

Thanks for Pransh Tiwari who was edited my function guardarNumeros(). 感谢Pransh Tiwari,他编辑了我的函数guardarNumeros()。

I was not be able to add snippet with my code because of stackoverflow's rules about too much code in the post so I wrote this phrase, sorry. 由于帖子中关于过多代码的规则,我无法在代码中添加代码段,所以我写了这句话,对不起。

 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'); 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; } 
 #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> 

upd 1: Kresimir, I have tryied: upd 1: Kresimir,我试过了:

function guardarNumeros() {
    boxvalue = document.getElementsByClassName('myInput');
    i = 0;
    var count = 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]
                tmp = rowsText.splice("Text", "Text", tmp[1], 0, tmp[2], "text");
                rowsText.push(tmp);
                i+=2;
            }
        } else {
            i++;
        }
    }
    console.log(rowsText);
    return false;
}

What I have got: 我所拥有的:

["1", 0, undefined, "text", Array(6), Array(6), Array(6), Array(6), Array(0)]0: "1"1: 02: undefined3: "text"4: (6) ["1", "X5CrNi18", "0", "55", "0", "Steel"]5: (6) ["2", "X5CrNi18", "100", "55", "0.5", "Steel"]6: (6) ["6", "S355J2Q +Z35", "100", "20", "0.68", "Steel"]7: (6) ["8", "S355J2Q +Z35", "300", "20", "0.3", "Steel"]8: []length: 9__proto__: Array(0)

upd 2: What I have before insert: upd 2:插入之前我所拥有的:

[
["1", "X5CrNi18", "0", "55", "0", "Steel"],
["2", "X5CrNi18", "100", "55", "0.5", "Steel"],
["6", "S355J2Q +Z35", "100", "20", "0.68", "Steel"],
["8", "S355J2Q +Z35", "300", "20", "0.3", "Steel"],
]

What I desire after insert: 插入后我想要什么:

     var count = 0;  
    [
        ["1", "X5CrNi18", "0", "55", "0", "Steel"],
        ["2", "X5CrNi18", "100", "55", "0.5", "Steel"],
        ["6", "S355J2Q +Z35", "100", "20", "0.68", "Steel"],
        ["8", "S355J2Q +Z35", "300", "20", "0.3", "Steel"],
        ["count++", "text value from text input", "value from input Num 1", "0", "value from input Num 2", "Just some default text"],
        ["count++", "text value from text input", "value from the next input Num 1", "0", "value from the next input Num 2", "Just some default text"]
]

EDIT: I completely misunderstood the question. 编辑:我完全误解了这个问题。 Here is an update: 这是一个更新:

Here is a minimalistic version of what I think you're trying to achieve: 这是我认为您要达到的目标的简约版本:

 document.getElementById("button1").addEventListener("click", () => { button1_clicked(); }); document.getElementById("button2").addEventListener("click", () => { button2_clicked(); }); let inputs = document.querySelectorAll("#container input[type='text']"); const container = document.getElementById("container"); const main_array = []; function button1_clicked() { const temp_array = []; for (i of inputs) { temp_array.push(i.value); } main_array.push(temp_array); console.log("main_array = ", main_array); } function button2_clicked() { container.innerHTML += `<br> <input type="text" value="test"> <input type="text" value="test">`; inputs = document.querySelectorAll("#container input[type='text']"); } 
 <div id="container"> <input type="text" value="test1"> <input type="text" value="test2"> </div> <button id="button1">Add to array</button> <button id="button2">Add more inputs</button> 

From my understanding of the problem this is the solution: 根据我对问题的理解,这是解决方案:

function guardarNumeros() {
    boxvalue = document.getElementsByClassName('myInput');
    i = 0;
    count = 0;
    defaultText = "Steel"
    while (i < boxvalue.length) {
        if (boxvalue[i].type == "number") {
            if (boxvalue[i+1] && boxvalue[i+1].type == "number") {
                textValue = document.getElementById('nameAlloy').value;
                tmp = [count, textValue, boxvalue[i].value, 0, boxvalue[i+1].value, defaultText]
                tmpARR.push(tmp);
                i+=2;
                count++;
            }
        } else {
            i++;
        }
    }
    console.log(tmpARR);
    return false;
}

Also to add the value of text easily, add id to it. 另外,要轻松添加文本的值,请向其添加ID。

<input type="text" class="myInput" name="nameAlloy" id="nameAlloy" placeholder="Name" >

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

相关问题 从子输入中获取ID值,并在更改时将其推入Javascript中的数组 - Get id values from child inputs and push it to an array in Javascript on change 如何将来自2个不同输入的值推入像这样的数组集[“ one”,2] - How to push the values from 2 different inputs into an array set like this [“one”, 2] 将所有输入 id 和值推入 json 数组 - Push all inputs ids and values into json array Javascript:如何在某些索引位置获取数组的值 - Javascript: How to get values of an array at certain index positions 如何将表单中的输入中的多个值推送到 mongoose.model 中的对象数组? - How can I push multiple values from inputs in a form to an array of objects in mongoose.model? 仅推入包含特定字符串的数组值 - Push in array only values ​that contain a certain string 从特定位置之间的数组中获取最大值 - Get max value from array between certain positions 将值推送到数组,并从数组打印值 - Push values to array, and print values from array 只要另一个键的值(在同一对象中)满足特定条件,就可以将数组中的所有键值推入新数组中 - Push all the key values from an array into a new array, so long as a different key's values (in the same object) meet a certain condition 使用2个不同输入从数组中获取值 - Get the values from array with 2 differents inputs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM