简体   繁体   中英

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'/>  ";
}

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);
}

使用jquery .append()将div添加到现有内容

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++;
        }
}

try this using pure javascript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM