且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用jQuery将行添加到表中

更新时间:2023-12-01 08:38:22

b
$ b

  $(document).ready(function(){
$('#btnAdd')。click(function(){
var count = parseInt($('#HowManyRows')。val()),first_row = $('#FirstRow');
while(count - > 0)
first_row.clone ().appendTo('#MainTable');
});
});

小提琴: http://jsfiddle.net/iambriansreed/QWpdr/


I have a HTML table which consists of 5 columns. Above the HTML table, there is a textbox called "HowManyRows" where the user may enter how many rows they would like to add to the table. The rows are actually added when the "Add Row!" button is clicked.

I thought the best way to create this functionality would be with a for loop, but after browsing the internet, people have said to use jQuery method .each. I've tried that, but it doesn't work as desired. It just adds one row to the table regardless of the number in "HowManyRows". Can someone correct where I have gone wrong please?

Here's my HTML:

    <input type="text" id="HowManyRows"/>
    <table id="MainTable">
        <tr id="FirstRow">
            <td>
            <select>
              <option>Milk</option>
              <option>Coffee</option>
              <option>Tea</option>
            </select>
            </td>
             <td>
            <select>
              <option>1 sugar</option>
              <option>2 sugar</option>
              <option>3 sugar</option>
           </select>
            </td>
             <td>
                 <input type="text"/>           
            </td>   
               <td>
                 <input type="text"/>           
            </td>
               <td>
                 <input type="text"/>           
            </td>
        </tr>  
    </table>
<button type="button" id="btnAdd">Add Row!</button>

Here's my jQuery:

$(document).ready(function () {
    $('#btnAdd').click(function () {
        $('#HowManyRows').each(function(index) {
            $('#FirstRow').clone().appendTo('#MainTable');
        });
    });   
});

I have created a demo on JSFiddle here.

Here you go:

 $(document).ready(function () {
     $('#btnAdd').click(function () {
            var count = parseInt($('#HowManyRows').val()), first_row = $('#FirstRow');
            while(count-- > 0)
                first_row.clone().appendTo('#MainTable');
     });   
 });​

Fiddle: http://jsfiddle.net/iambriansreed/QWpdr/