简体   繁体   English

HTML如何在按钮单击时添加唯一的输入元素

[英]HTML how to add unique input element on button click

Hi I am trying to figure out how to add input element on button click using plain javascript to be used latter for sending data to backend.嗨,我想弄清楚如何使用普通 javascript 在按钮单击时添加输入元素,以便后者用于将数据发送到后端。

<div class="myDiv">
<input type="text" id="inputData" name="selectOption">
        <select id="optionData">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="opel">Opel</option>
            <option value="audi">Audi</option>
        </select>
<div class="myDiv">

<input type="button" value="Add element" onclick="AddElement()">

I would be using that to send data to the backend.我将使用它向后端发送数据。 The only approach that I could think of was declare a global javascript array and use it to store it我能想到的唯一方法是声明一个全局 javascript 数组并使用它来存储它

var elements = [];
function AddElement() {
  const inputData = document.getElementById("inputData").value;
  const optionData = document.getElementById("optionData").value;
  const data = {
    inputData: inputData,
    optionData: optionData
  };
  elements.push(data);
  // create new element in dom with the data and random ids and clear the inputData and optionData element.
}

The problem with the above is that changes to existing element would not reflect in the global array.上面的问题是对现有元素的更改不会反映在全局数组中。

Could someone suggest a better approach?有人可以提出更好的方法吗?

It is a bit uncleaner how will you send data to server etc and I see there is some confusion on technique how to achieve this.如何将数据发送到服务器等有点不清晰,我看到在如何实现这一点的技术上存在一些混淆。 So I will cover two scenarios.所以我将介绍两种情况。 Both will make new input fields out of your initial select and input as requested and additionally quid how to send them to server.两者都将根据要求从您的初始selectinput创建新的输入字段,并另外询问如何将它们发送到服务器。

I will not make unique ids or name attributes on those fields because that would mean you would need to know in front what ids or names are generated and fetch them on server side on submit, instead when submitting a form using HTML and PHP, we will make array with input names attribute.我不会在这些字段上创建唯一的idsname属性,因为这意味着您需要在前面知道生成了哪些idsnames并在提交时在服务器端获取它们,而不是在使用 HTML 和 PHP 提交表单时,我们将使用input names属性制作array Case with JS sending data to server will be similar using arrays. JS 向服务器发送数据的情况与使用数组类似。

First way using PHP and setting form inputs names as array:第一种使用 PHP 并将表单输入名称设置为数组的方法:

1 - Create a form below your input and select 1 - 在您的输入下方创建一个表单并选择

<form id="result">
...
</form>

2 - On click of button, save data into variable like you did, then clear those fields: 2 - 单击按钮,像您一样将数据保存到变量中,然后清除这些字段:

document.getElementById("inputData").value="";
document.getElementById("optionData").value="";

3 - Then create two input fields, fill them with data and append them into form: 3 - 然后创建两个输入字段,用数据填充它们并将它们附加到表单中:

document.querySelector("#result").innerHTML +=
 '<input type="text"  name="inputData[]" value="'+inputData+'">
<input type="text"  name="optionData[]" value="'+optionData+'"><br>';

4 - One of the input fields will have name="inputData[] " other will have name="optionData[]" . 4 - 输入字段之一将具有name="inputData[] " 其他将具有name="optionData[]" Notice the [] sign, that will on form submit create on array.注意[]符号,它将在表单上提交创建数组。 Then or server side for example with PHP you catch that array and use foreach() to send them to server as keys and values .然后或服务器端例如使用 PHP 捕获该数组并使用foreach()将它们作为keysvalues发送到服务器。 Please read more about this here: Posting Form Fields with same Name Attribute请在此处阅读更多相关信息: 发布具有相同名称属性的表单字段

EXAMPLE SNIPPET:示例片段:

 var elements = []; function AddElement() { const inputData = document.getElementById("inputData").value; const optionData = document.getElementById("optionData").value; // create new element in dom with the data and random ids and clear the inputData and optionData element. document.getElementById("inputData").value=""; document.getElementById("optionData").value=""; //clear the inputData and optionData element. document.querySelector("#result").innerHTML += '<input type="text" name="inputData[]" value="'+inputData+'"><input type="text" name="optionData[]" value="'+optionData+'"><br>'; // add new line with 2 inputs, one is inputData other is optionData }
 <div class="myDiv"> <input type="text" id="inputData" name="selectOption"> <select id="optionData"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <form id="result"> </form> <input type="button" value="Add element" onclick="AddElement()"> </div>

Sending data with JS can be done in multiple ways.可以通过多种方式使用 JS 发送数据。 You could use above HTML markup and then catch all form data like this:您可以使用上面的 HTML 标记,然后像这样捕获所有表单数据:

//EXAMPLE USING JS TO GET FORM DATA
var formData = new FormData(document.querySelector('#result'))
console.clear()
for (var pair of formData.entries()) {
    console.log(pair[0]+ ' - ' + pair[1]); 
    // here you could send AJAX data to server for each entry 
}

Please read more about how to How can I get form data with JavaScript/jQuery?请阅读有关如何使用 JavaScript/jQuery 获取表单数据的更多信息

SNIPPET EXAMPLE:片段示例:

 var elements = []; function AddElement() { const inputData = document.getElementById("inputData").value; const optionData = document.getElementById("optionData").value; // create new element in dom with the data and random ids and clear the inputData and optionData element. document.getElementById("inputData").value=""; document.getElementById("optionData").value=""; //clear the inputData and optionData element. document.querySelector("#result").innerHTML += '<input type="text" name="inputData" value="'+inputData+'"><input type="text" name="optionData" value="'+optionData+'"><br>'; // add new line with 2 inputs, one is inputData other is optionData //EXAMPLE USING JS TO GET FORM DATA var formData = new FormData(document.querySelector('#result')) console.clear() for (var pair of formData.entries()) { console.log(pair[0]+ ' - ' + pair[1]); // here you could send AJAX data to server for each entry } }
 <div class="myDiv"> <input type="text" id="inputData" name="selectOption"> <select id="optionData"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <form id="result"> </form> <input type="button" value="Add element" onclick="AddElement()"> </div>

Or you could like you intended save them into arrays on initial creation per each row and send items using AJAX without even using HTML form.或者,您可能希望在每行初始创建时将它们保存到数组中,并使用 AJAX 发送项目,甚至不使用 HTML 表单。

AND TO answer the question how to create unique ids, names or classes: Declare i variable as number 0 outside of click function:并回答如何创建唯一 ID、名称或类的问题:在 click 函数之外将i变量声明为数字0

i="0";
//set initial unique number i

then inside click call it like this ++i this will result in optionData1 , optionData2 etc on every ++i initiation:然后在点击里面像这样调用它++i这将导致每次++i启动时的optionData1optionData2等:

name="optionData'+(++i)+'"

you can use it on ids, classes or anything:你可以在 ids、classes 或任何东西上使用它:

id="newId'+(++i)+'"

newid1 , newid2 etc... newid1newid2等...

But like i said, you cant really generate unique ids or anything because you can not program them in front to use them to send fields to server.但就像我说的,你不能真正生成唯一的 id 或任何东西,因为你不能在前面对它们进行编程以使用它们将字段发送到服务器。

Example:例子:

 var elements = []; i = "0"; //set initial uniqe number i function AddElement() { const inputData = document.getElementById("inputData").value; const optionData = document.getElementById("optionData").value; // create new element in dom with the data and random ids and clear the inputData and optionData element. document.getElementById("inputData").value = ""; document.getElementById("optionData").value = ""; //clear the inputData and optionData element. document.querySelector("#result").innerHTML += '<input type="text" name="inputData' + (++i) + '" value="' + inputData + '"><input type="text" name="optionData' + (++i) + '" value="' + optionData + '"><br>'; // add new line with 2 inputs, one is inputData other is optionData // use ++i to generate last number plus, and just add it to some name, id or class; name="optionData'+(++i)+'" console.clear(); [...document.querySelectorAll('#result > input')].forEach(input => { console.log(input.getAttribute("name")); }) }
 <div class="myDiv"> <input type="text" id="inputData" name="selectOption"> <select id="optionData"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <form id="result"> </form> <input type="button" value="Add element" onclick="AddElement()"> </div>

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

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