1

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.

5 Answers 5

2

.each() doesn't seem useful here, as it's typically used for iterating over a collection of jQuery-selected elements. A simple loop would work:

$('#btnAdd').click(function () {
    var n = parseInt($('#HowManyRows').val(), 10);
    var original = $('#FirstRow');
    for (var i = 0; i < n; i++) {
        original.clone().appendTo('#MainTable');
    }
});
Sign up to request clarification or add additional context in comments.

7 Comments

and in this case you'd like to count the button clicks and not number of rows, that's why for() loop vs. each()?
@tim - I'm not sure I follow your second question there.
@RobHruska, i'm still confused on your explanation, "each... is typically used for iterating over a collection of jQuery-selected elements/". Can you maybe compare/contrast each() vs. for() in this case?
@tim - To me that would seem redundant - I feel that the .each() documentation and basic knowledge of what a for loop does ought to be enough here.
@tim - No problem, I don't think you did. I just didn't want to go off in an unnecessarily-detailed copy of the documentation here.
|
2

Using the jQuery .clone() method as others have suggested is not recommended for this situation as per jQuery docs:

Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

Not to mention that the suggested method of looping through .appendTo() calls will cause the client to re-render every iteration. I suggest the following:

Create a constant that is your row template:

var row = ['<tr id="',
           '', // Insert id value here
           '"><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>'];

Alternatively, you could omit the id in the row variable and have just one big string if each row does not need a unique id. You then continue with:

$('#btnAdd').click(function () {
    var i = parseInt($('#HowManyRows').val(), 10);
    var cnt = i;
    var rowCnt = $('#MainTable').children().length;
    var rows = [];
    while(i--) {
        row[1] = 'row' + (rowCnt + cnt - i);
        rows.push(row.join()); // or just row if not using the id
    }
    $('#MainTable').append(rows.join());
}

This way we only have a one-time addition to the DOM, and the empty string element in our row variable is replaced with a unique and predictable id.

2 Comments

hi thanks for the information and examples, how could i create a unique id for each row created? as im looking in to that now, and have only just seen your comment...
In the example click function I have: row[1] = 'row' + (rowCnt + cnt - i); This will give each added row an id like 'row1', 'row2', 'row3', ...
1

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/

7 Comments

FWIW, you ought to specify the radix when using parseInt().
Side note. Put the number of rows to add box next to the button for usability.
Hi sorry i for got to ask this but what is --> next to count? could i not just say count > 0 ?
count-- is a short hand way of saying count - 1, so 1 is subtracted from count after it is compared to 0. See w3schools.com/js/js_operators.asp and read about decrement.
@iambriansreed - MDN recommends it, and I like MDN. I would say it's more prudent when taking user input.
|
0
$(document).ready(function () {
    var $howMany = $('#HowManyRows'),
        $firstRow = $('#FirstRow');
    $('#btnAdd').click(function () {
        var numRows = parseInt($howMany.val(), 10) || 1; //default to 1
        for (var i = 0; i < numRows; i++){
            $firstRow.clone().appendTo('#MainTable');
        }
    });   
});

Comments

0

each iterates over the elements in the jQuery object its called on, so this:

$('#HowManyRows').each(...);

only executes one iteration, because $('#HowManyRows') only has one element in it.

In your case, a loop is perfectly acceptable.

var howMany = parseInt($('#HowManyRows').val(), 10);
while (howMany-- > 0) {
    // Add a row...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.