Add New Table Row after current row using jQuery
Solution 1
$(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');
});
Solution 2
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');
});
And you should consider using $.on as $.live is depreciated now
Related videos on Youtube
KoolKabin
A freelance web developer Websites: 1.) http://biotechx.com 2.) http://highcountrytrekking.com 3.) http://firante.com 4.) http://himalayanencounters.com 5.) http://ajisai.edu.np 6.) http://environmentnepal.info/test 7.) http://treknepal.au 8.) http://sunshinetrekking.com 9.) http://taverntrove.com 10.) http://trekkingandtoursnepal.com 11.) http://outsourcingnepal.com
Updated on September 15, 2022Comments
-
KoolKabin over 1 year
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>
-
VisioN almost 12 yearsPlease add also your markup to the question.
-