Jeevan Roy dsouza
Jeevan Roy dsouza

Reputation: 673

Dont want to Clear text box while clicking add button

i have one requirements for adding text box while clicking button. When i am clicking add button new text box will be created But previousely entered data in text box will be cleared.I dont want to clear the data in text box while clicking add button. How i can resolve this problem?

html

<tr id="div"></tr>
<tr> 
 <td> 
  <button type="button" class="btn btn-lg btn-info" onclick="generateRow();">Add</button>
 </td>
</tr>

JS

function generateRow() {
   var d=document.getElementById("div");
   d.innerHTML+=" <input class='form-control' type='text' required autofocus name='year'/>  ";
}

Upvotes: 1

Views: 820

Answers (5)

bjb568
bjb568

Reputation: 11488

function generateRow() {
    var i=0,j=0;

    var d=document.getElementById("div"),input,value;
    //var m=document.getElementById("div");
    var x=new Array(50);
    while (i!=d.childNodes.length/2)
    {
    if (input = d.children[i]) {// If there's an input...
        x[i]=input.value; // ...get the value
    }


    //d.children[i].value = value;
    i++;
    }
    d.innerHTML += "<input class='form-control' type='text' required autofocus name='year'/> ";
  //  m.innerHTML += "<td><input  type='button' required autofocus name='year' value='Remove'/> </td>";

    while(j!=i)
        {
    d.children[j].value = x[j];
        j++;
        }
}

Upvotes: 1

Rohit Awasthi
Rohit Awasthi

Reputation: 686

try this using pure javascript

function generateRow() {
    var d=document.getElementById("div");
    var f = document.createElement("input");
    f.name="year";
    d.appendChild(f);
}

Upvotes: 1

TheMohanAhuja
TheMohanAhuja

Reputation: 1875

you can use something like this in javascript

function generateRow() {
    var child="<input class='form-control' type='text' required autofocus name='year'/>"; 
    document.getElementById("div").appendChild(child);
}

Upvotes: 2

Krimson
Krimson

Reputation: 7664

A slightly different answer using jQuery. Might be useful for future users

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script  type="text/javascript">
        function generateRow() {
            $("#div").append("<input type='text' name='year'/><br/>");
        }
    </script>
</head>
<body>
    <table>
        <div id="div">
            <!-- Buttons Go Here -->
        </div>
        <button type="button" onclick="generateRow();">Add</button>
    </table>
</body>
</html>

JSFiddle

Upvotes: 0

Manojkumar
Manojkumar

Reputation: 1361

use jquery .append() to add div to the existing content

Upvotes: 1

Related Questions