简体   繁体   中英

Adding rows dynamically into HTML

Here is what I have got after a lot of research , so though I will share it ,

Please let me know if I can optimize it more. This code adds a new row on clicking the add row, and also dynamically assigns id and name.

        <script type="text/javascript">
        $(document).ready(function(e) {
        //n:variable for generating dynamic values
        var n=1;
        $("#add").click(function() {    
        n++;

       // converting HTML to JS readable format
       var strVar="";
       strVar += "<tr>";
       strVar += "        <td id=\"day\">Day ";
       strVar += n;
       strVar +=" <\/td>";
       strVar += "        <td><textarea name=\"" ;
       strVar += n;
       strVar +="\"cols=\"50\" rows=\"10\" id=\"" 
       strVar += n;
       strVar +="\"><\/textarea><\/td>";
       strVar += "      <\/tr>";

     $(strVar).insertAfter("#mytable tr:nth-last-child(3)");
             document.getElementById("h").value= n;     
             return false;
             });

      });

   </script> 

HTML

    <table>
    <tr id="test">
      <td id="day">Day 1</td>
      <td><textarea name="1" cols="50" rows="10" id="1"></textarea></td>
    </tr>




  <tr><td>&nbsp;</a></td><td><a href="#" id="add" style="color:#00F">Add another Day</td>   </tr>
  <tr>
    <!-- sending hidden field with the number of fields generated for entering into db using php-->
    <td>&nbsp; <input type="hidden" id="h" value=""/>  </td>
    <td><input type="image" name="button"  src="../images/admin/submit.png" onMouseOver="this.src='../images/admin/submit_hover.png'" onMouseOut="this.src='../images/admin/submit.png'" id="button" value="Add this Item now"></td>
  </tr>
  </table>

documentfragment is here to create fast dom nodes.

var f=document.createDocumentFragment();
for(var a=0;a<5;a++){
 var field=document.createElement('td');
 field.textContent='field '+a;
 f.appendChild(field);
}
yourTable.appendChild(document.createElement('tr')).appendChild(f);

slower but short.

var tr='<tr><td>field '+['1','2','3','4','5'].join('</td><td>field ')+'</td></tr>';

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