Add new row table after current row using jQuery

I am trying to add a new line which is a clone of the current line. I tried the following code. It does not cause an error, but does not add a line. What is the error here with my code? Is there an 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> 
+6
source share
3 answers

$(this).parent('tr') will not find anything. Your input element will be inside either td or th . parent only detects the immediate parent, and then compares it to the selector you select. Therefore, he will not find anything. Then you clone nothing and insert a new nothing after the old nothing. Perhaps unsurprisingly, this actually does nothing.

You need to use closest , which finds the closest element according to the selector

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

Note that you are using global variables since you are not using var (I am fixing this in the line above), which you probably do not want to do. In addition, live 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'); }); 
+13
source

You must use $. nearest 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 script

And you should consider using $. on , because $ .live is now depreciating

+1
source

use on instead of live , live deprecated since recent jQuery versions, your parent() selects the td element, use the parent() or closest('tr') methods:

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

http://jsfiddle.net/qVm75/3/

0
source

Source: https://habr.com/ru/post/916903/


All Articles