Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add New Table Row after current row using jQuery

I'm trying to add new row which is clone of current row. I tried following code. It doesn't pops error but neither adds rows. Whats the error here with my code? Is there any alternative easy idea?

        $('input[name="cmdAddRow"]').live('click', function(){
            $curRow = $(this).parent('tr');
            $newRow = $curRow.clone(true);
            console.log($newRow);
            $curRow.after($newRow);
            console.log('added');
        });

HTML Layout:

<table>
    <tr>
        <td><input type="hidden" name="uin" value="xxx"></td>
        <td><input type="text" name="uname" value=""></td>
        <td><input type="text" name="uadd" value=""></td>
        <td><input type="text" name="utel" value=""></td>
        <td><input type="button" name="cmdAddRow" value="Add"></td>
    </tr>
</table>
like image 984
KoolKabin Avatar asked May 29 '12 11:05

KoolKabin


2 Answers

$(this).parent('tr') will not find anything. Your input element will be inside either a td or a th. parent only finds the element's immediate parent, then compares it against the selector you provide. It will therefore find nothing. You then clone nothing, and insert the new nothing after the old nothing. Perhaps unsurprisingly, this doesn't actually do anything.

You need to use closest, which finds the nearest element to match a selector

var $curRow = $(this).closest('tr');

Note also that you are using global variables, since you're not using var (I correct this in the line above), which you probably don't want to do. Furthermore, live is not a good function to use; use on instead, which does the same thing more elegantly:

$('#yourTable').on('click', 'input[name="cmdAddRow"]', function() {
    var $curRow = $(this).closest('tr'),
        $newRow = $curRow.clone(true);
    console.log($newRow);
    $curRow.after($newRow);
    console.log('added');
});
like image 92
lonesomeday Avatar answered Sep 28 '22 03:09

lonesomeday


You have to use either $.closest or $.parents instead of $.parent like this

 $('input[name="cmdAddRow"]').live('click', function(){
        $curRow = $(this).closest('tr');
        $newRow = $curRow.clone(true);
        console.log($newRow);
        $curRow.after($newRow);
        console.log('added');
    });​

Working Fiddle

And you should consider using $.on as $.live is depreciated now

like image 26
Prasenjit Kumar Nag Avatar answered Sep 28 '22 02:09

Prasenjit Kumar Nag