mkautzm
mkautzm

Reputation: 1146

tr:last not selecting last row when I add rows with .after in jquery

I have some table that looks like so:

<table width="600" border="1" id="mytable">
    <tbody>
        <tr>
            <td width="300">col1</td>
            <td width="100">col2</td>
            <td width="100">col3</td>
            <td width="100">col4</td>
        </tr>
        <tr>
            <td width="300"><input type="text"></td>
            <td width="100"><input type="text" size="12"></td>
            <td width="100"><input type="text" size="12"></td>
            <td width="100">&nbsp;</td>
        </tr>
        <tr>
            <td width="300"><input type="text"></td>
            <td width="100"><input type="text" size="12"></td>
            <td width="100"><input type="text" size="12"></td>
            <td width="100">&nbsp;</td>
        </tr>
        <tr>
            <td width="300"><input type="text"></td>
            <td width="100"><input type="text" size="12"></td>
            <td width="100"><input type="text" size="12"></td>
            <td width="100">&nbsp;</td>
        </tr>
    </tbody>
    </table>

I then wish to be able to dynamically expand this table by simply checking to see if the last row has any values in it. If it does, I want to expand it and if it doesn't, I just let it be. Right now, I'm accomplishing this by listening for a keypress event:

    $("#mytable tr:last input").keypress(function () {
    autoAddRow();
    });

which references this:

var _addRow = '<tr><td width="300"><input type="text" id="name"></td><td width="100"><input type="text" size="12" id="units"></td><td width="100"><input type="text" size="12" id="value"></td><td width="100">&nbsp;</td></tr>';


function autoAddRow()
{
    if($('#mytable > tr:last > name').val() != "" || $('#mytable > tr:last > units').val() != ""|| $('#mytable > tr:last > value').val() != "")
    {
        $('#mytable tr:last').after(_addRow);
    }
}

This works, except that when it adds a row, it doesn't treat that like the last row for the purposes of tr:last selection. In this case, the third row (the last row that is hard-coded) is always what is being checked as the final row in the table.

How can I force it to check the final row of the table as it expands dynamically, or otherwise reproduce this functionality.

Upvotes: 2

Views: 1470

Answers (1)

dsgriffin
dsgriffin

Reputation: 68616

As the elements are dynamically added, you want to be using event delegation here:

$(document).on('keypress', '#mytable tr:last input', function () {
   autoAddRow();
});

Working jsFiddle.

Upvotes: 2

Related Questions