【问题标题】:How to get the value of dynamic textbox input如何获取动态文本框输入的值
【发布时间】:2018-03-22 03:12:02
【问题描述】:

我创建了一个动态创建文本框的函数,我得到了第一个文本框的值,因为它是在我的 HTML 中创建的......

但我无法从我的addInput 函数中获取任何其他文本框的值。我想在我的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');">

如您所见,“案例 1”的值可以发送,但“案例 2”的值不能发送。任何帮助,将不胜感激。谢谢。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    有一些错误:

    您不能拥有多个具有相同ID 的元素。在 addInput 函数中,ID os 是硬编码的,并且对于添加的所有元素都是相同的:

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

    addQuestion 函数中,您尝试通过 ID 'testecases' 获取元素,但新元素的 id='case':

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

    要修复错误,请从动态添加的输入中删除 ID,并尝试按名称获取元素:

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

    【讨论】:

    • 您好,感谢您的回复。我将如何获得所有输入的值,以便我可以将其发送到myJSONObject
    • 使用forEach循环元素:testcases.forEach((i) =&gt; console.log(i.value) );你可以得到i.value并添加到数组并序列化,或者用值构建一个字符串
    【解决方案2】:

    您可以使用 querySelectorAll 选择所有属于 #cases 子级的输入:

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

    如果要将所有值放入数组并发送:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2013-06-07
      • 2011-05-04
      相关资源
      最近更新 更多