简体   繁体   English

如何获取动态文本框输入的值

[英]How to get the value of dynamic textbox input

I created a function that dynamically creates textboxes, and I am getting the value of the first textbox because it's created in my HTML... 我创建了一个动态创建文本框的函数,由于第一个文本框是在HTML中创建的,因此我得到了它的值。

but I can't get the values of any other textboxes from my addInput function. 但是我无法从我的addInput函数获取任何其他文本框的值。 I would like to get the value in my addQuestion function like how I did for the testcases . 我想在我的addQuestion函数中获取值,就像我对测试用例所做的那样

 function addInput(divID) { if (counter == limit) { alert("You have reached the limit of adding " + counter + " inputs"); } else { var newdiv = document.createElement('div'); newdiv.innerHTML = "Case " + (counter + 1) + " <br><input type='text' name='myInputs[]' id='case'>"; document.getElementById(divID).appendChild(newdiv); counter++; } } function addQuestion() { var request = new XMLHttpRequest(); var testcases = document.getElementById("testcases").value; var myJSONObject = { "testcases": testcases }; console.log(JSON.stringify(myJSONObject)); request.open("POST", "createQuestion_middle.php", true); request.send(JSON.stringify(myJSONObject)); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var return_data = request.responseText; console.log(return_data); /* window.location.assign("insFront.php"); */ } } } 
 <div id="cases"> Case 1<br><input type="text" id="testcases" name="myInputs[]"> </div> <input type="button" value="Add another test case" onClick="addInput('cases');"> 

As you can see, the value for "Case 1" can send, but not for "Case 2". 如您所见,“案例1”的值可以发送,但“案例2”的值不能发送。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

在此处输入图片说明

You can select all inputs that are children of #cases with querySelectorAll: 您可以使用querySelectorAll选择所有属于#case子级的输入:

const inputs = document.querySelectorAll('#cases > input')
console.log(inputs[0].value);
console.log(inputs[1].value);

If you want to put all values into an array and send it: 如果要将所有值放入数组并将其发送:

const inputValues = [...inputs].map(input => input.value);
// ...
const myJSONObject = { testcases: inputValues };

There are some erros: 有一些错误:

You cannot have more than one element with same ID . 同一ID不能包含多个元素。 In addInput function, the ID os hard-coded, and will be the same for all elements added: addInput函数中, ID硬编码的,并且对于添加的所有元素都是相同的:

<input type='text' name='myInputs[]' id='case'>

In addQuestion function, you're trying to get element by ID 'testecases', but new elements have id='case': addQuestion函数中,您尝试通过ID'testecases'获取元素,但是新元素的ID为'case':

var testcases = document.getElementById("testcases").value

To fix the errors, remove ID from dynamically added inputs, and try to get elements by name: 要修复错误,请从动态添加的输入中删除ID,然后尝试按名称获取元素:

var testcases = document.getElementsByName("myInputs[]")

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

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