Reputation:
I have a situation where a need to add rows after clicked row in table
For that I know this
$('table tr:nth-child(2)').after(tr); // which is working but its static.
My requirement is to take row number of clicked row which I am taking with below function
$('#data-grid-table-tree').find('tr').click(function () {
rowNumber = ($(this).index() + 1)
});
And now I am using $('table tr:nth-child(rowNumber)').after(tr);
which throwing below error
Uncaught Error: Syntax error, unrecognized expression: :nth-child
Why it is? How to use dynamic value for nth:child.
Upvotes: 2
Views: 824
Reputation: 87203
As rowNumber
is variable and you need it's value in the selector use +
$('table tr:nth-child(' + rowNumber + ')').after(tr);
You can also use eq as follow
$('table tr').eq(rowNumber).after(tr);
As the indexing of eq
starts from zero, there's no need of adding 1
to the index.
$('#data-grid-table-tree tr').click(function () {
rowNumber = $(this).index(); // Removed `+ 1` from here
});
Edit:
You can also use $(this)
to refer to the element that is clicked and use after
on it.
$('#data-grid-table-tree tr').click(function () {
// Code here
$(this).after(tr);
});
Upvotes: 1
Reputation: 18123
You bind the click event on the tr
, why not use that to your advantage. You want to place the new tr
right after it. So instead of using its index, insert it direct after the clicked element.
$('#data-grid-table-tree').on('click', 'tr', function() {
$(this).after(tr);
});
Upvotes: 0