how do i retain the value of dynamically added textboxes

江枫思渺然 提交于 2019-12-13 08:57:34

问题


i am using this code:

<html>
 <head>
   <title>Dynamic Form</title>
   <script type="text/javascript">
     var i = 6;
    function CreateTextbox(){
      createTextbox.innerHTML = createTextbox.innerHTML 
                   +'<input type=text name="flow'+i+'"/>'
       i++;
    }
  </script>
</head>
<body>
 <form name="form" action="post">
  <input type="button" name="what" value="clickHere" onClick="CreateTextbox()"/>
   <div id="createTextbox"></div>
 </form>
</body>

when i add a new textbox, the value that was entered in the previous textbox is deleted. how can i retain it?


回答1:


Adding HTML element by concatenating the innerHTML is very slow and that is causing the values to be cleared, since the container (the div createTextbox) and all the childs are re-created on each innerHTML assignment.

I suggest you to create the input elements programmatically with document.createElement and append the elements using to the container div using appendChild:

window.onload = function  () {

  var createTextbox = function () {
    var i = 6,
        container = document.getElementById('createTextbox');

    return function () {
      var div = document.createElement('div'),
          input = document.createElement('input');
      input.type= "text";
      input.name = "flow" + i;
      div.appendChild(input);
      container.appendChild(div);
      i++;
    }
  }();

  // event binding
  document.getElementById('addButton').onclick = createTextbox;
}

Check the above code working here.




回答2:


You're probably forcing the browser to recreate the element when you redefine its innerHTML property, which subsequently causes you to lose its value in the process.

Can this be done with a

  var elem = document.createElement("input");
  someDOMElement.childNodes.add(elem);

combination?



来源:https://stackoverflow.com/questions/1391875/how-do-i-retain-the-value-of-dynamically-added-textboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!