Add New Table Row after current row using jQuery
clone, event-handling, jquery
Solution
`$(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');
});
Problem
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> ```