tags:

views:

281

answers:

4

I added a jquery function to add a <tr> dynamically at the end of my table. It worked fine until I added table headers to my table. After I did this, the function started adding 2 trs at a time to the table. What happened?

HTML:

<table id="table" border="0">
<th>Col 1</th><th>Col2</th><th>col3</th>
<tbody>
<tr>
    <td>
        <select>
            <option value ="one">one</option>
            <option value="two">two</option>
        </select>
    </td>
    <td>
        <input type="text"></input>
    </td>
    <td>
        <input type="text"></input>
    </td>
</tr>
</tbody>
</table>

JQuery code:

$(function(){
  $('a#add').click(function(){
    $('#table > tbody').append('<tr><td><select><option value ="one">one</option><option value="two">two</option></select></td><td><input type="text"></input></td><td><input type="text"></input></td></tr>');  
  });
+2  A: 

The browser is going to compensate for your code by surrounding your th with another tbody. Try surrounding the th's with a thead.

<table id="table" border="0">
    <thead>
        <th>Col 1</th><th>Col2</th><th>col3</th>
    </thead>
    <tbody>
        <tr>
            <td>
                <select>
                    <option value ="one">one</option>
                    <option value="two">two</option>
                </select>
            </td>
            <td>
                <input type="text"></input>
            </td>
            <td>
                <input type="text"></input>
            </td>
        </tr>
    </tbody>
</table>
Mike Robinson
+1 More explanation than my answer ;)
Josh Stodola
A: 

If you are going to use tbody, you need to use thead as well.

Josh Stodola
A: 

Add a :last to your selector like so (demo, source):

$(function(){
  $('a#add').click(function(){
    $('#table > tbody:last').append('<tr><td><select><option value ="one">one</option><option value="two">two</option></select></td><td><input type="text"></input></td><td><input type="text"></input></td></tr>');  
    return false;
  });
});

Since your headers are not part of tbody or thead, the browser automatically creates a tbody for them. Thus your rendered table has two tbodys. The better solution is to keep your current selector and put the header in a thead section like this:

<thead>
<th>Col 1</th><th>Col2</th><th>col3</th>
</thead>

Or just put it in the already existing tbody so the browser won't make a new one.

Michael Haren
A: 

Remove the > tbody from you jQuery selector. It worked fine for me after that.

$('a#add').click(function(){
  $('#table').append('<tr><td><select><option value ="one">one</option><option value="two">two</option></select></td><td><input type="text"></input></td><td><input type="text"></input></td></tr>');  
});
Dustin Laine