how do i retain the value of dynamically added tex

2019-09-20 15:05发布

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?

2条回答
你好瞎i
2楼-- · 2019-09-20 15:41

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.

查看更多
看我几分像从前
3楼-- · 2019-09-20 15:56

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?

查看更多
登录 后发表回答