从动态创建的javascript文本框中获取文本输入

时间:2015-03-03 19:58:08

标签: javascript

我正在使用此链接中的代码。 http://www.randomsnippets.com/2008/02/21/how-to-dynamically-add-form-elements-via-javascript/

var counter = 1;
var limit = 3;
function addInput(divName){
    if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + "    inputs");
     }
     else {
          var newdiv = document.createElement('div');
           newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input    type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
         }
 }

如何从文本输入中获取值?

2 个答案:

答案 0 :(得分:0)

将id attr添加到input:

newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input    type='text' name='myInputs[]' id='"+counter+"'>";

然后你不能写:

var x = document.getElementById("1").value;

答案 1 :(得分:0)

首先获取文档中的所有输入元素,并使用您设置“myInputs []”的名称过滤输入,然后循环并获取输入值。

var inputEle = document.getElementsByTagName("input");
    var inputNewlyAdded = [];
    for(var i = 0 ; i < inputEle.length ; i ++){
      if(inputEle[i].name == "myInputs[]"){
         inputNewlyAdded.push(inputEle[i]);
      }
    }

    for(var j = 0 ; j < inputNewlyAdded.length ; j ++){
      console.log(inputNewlyAdded[j].value);
    }