Ahad Porkar
Ahad Porkar

Reputation: 1708

Dynamically inserted table: last row not detected by JQuery

I'm using JQuery for creating dynamic table row based on user insertion.

My HTML:

     <table id="list">
            <thead>
              <tr>
                <th>first header</th>
                <th>second header</th>
                <th>third header</th>
              </tr>
            </thead>
             <tbody>
               <tr>
                 <td><input type="text" name="first" /></td>
                 <td><input type="text" name="second" id="second" /></td>
                 <td><button class="alert hollow button" href="#">X</button>                 </td>
               </tr>
             </tbody>
     </table>

And JavaScript:

$('#list tr:last td:nth-last-child(2) input[name=second]').keyup(function (event) {

    if ($(this).val().length > 4 && $('#list tr:last td:nth-last-child(2) input[name=second]').val().length > 4) {
        $('#list tbody').append('<tr>
                     <td><input type="text" name="first" /></td>
                     <td><input type="text" name="second" id="second" /></td>
                     <td><button class="alert hollow button" href="#">X</button></td>
                   </tr>');
    }
});

The above code only works for the first row and the inserted row has no JS code-behind.

Upvotes: 0

Views: 702

Answers (2)

Velimir Tchatchevsky
Velimir Tchatchevsky

Reputation: 2825

Your function does not bind to elements that don't exist on page load, use on for dynamically generated elements

$(document).on('keyup', '#list tr:last td:nth-last-child(2) input[name=second]', function (event) {

Upvotes: 1

NachoDawg
NachoDawg

Reputation: 1544

You haven't given complete code, but i suspect this is your issue..

Replace this

$('#list tr:last td:nth-last-child(2) input[name=second]').keyup(function (event)

with this

$('#list').on('keyup', 'tr:last td:nth-last-child(2) input[name=second]', function (event)

You are probably not using proper event delegation, and you're trying to bind a keyup event on an element that doesn't exist yet (you say the rows are added dynamically). Instead we bind the keyup to the table that is part of the initial document, and say what happends when a child that meets X criteria has a keyup event fired

Upvotes: 2

Related Questions