views:

315

answers:

3

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?

A: 

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?

David Andres
A: 
<html>
     <head>
       <title>Dynamic Form</title>
       <script type="text/javascript">
        function CreateTextbox(){
          createTextbox.innerHTML = createTextbox.innerHTML 
                       +'<input type=text name="flow"/>'
        }

        function getValues(){
          if(form1.flow!=null){
            if(form1.flow.length==null)
               alert(form1.flow.value);
            else{
            for(i=0;i<form1.flow.length;i++){
              alert(form1.flow[i].value);
             }
            }
           }
        }
      </script>
    </head>
    <body>
     <form name="form1" action="post">
      <input type="button" name="what" value="clickHere" onClick="CreateTextbox()"/>
       <div id="createTextbox"></div>
      <input type="button" name="GetValue" onclick="getValues()"/>
     </form>
    </body>
adatapost
+1  A: 

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.

CMS