0

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>

1 Answer 1

1

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>';
Sign up to request clarification or add additional context in comments.

6 Comments

Why don't you append the td directly in the tr?
because documentfragment is here to create fast dom nodes
Why should be faster?
test it jsperf or console.time().why should it be slower?? i prefer fast sites. anyway i posted 2 solutions i like .. you can choose whatever you want.
Well, I asked why, not how you could prove it. Also, I think it isn't the same for different browser.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.