Reputation: 4919
I have a table (id of the table is county_table) with plenty of lines like this:
<tr>
<td><input class="text" type=text name=param1 maxlength=2 size=2></td>
<td><select class="text" name=param2><option value=1>Live<option value=2>Test</select></td>
<td><input class="text" type=text name=param3 ></td>
<td><input class="text" type=text name=param4 ></td>
<td><input class="text" type=text name=param5 ></td>
<td><input class="text" type=text name=param6 ></td>
<td colspan=2><input class="button" type=submit value=New onclick="function_new($('#county_table tr:eq(1)'))"></td>
</tr>
The onclick function would manage the table data, and maybe send an AJAX, so I need to get the all elements of the table.
The bad thing with that solution is that if I insert a new row the whole table row selection would be messed up, so I'd like to change the tr:eq(1)
, something like this.tr
or something like that, is the button know his ancestor and get the given object?
I would appreciate any help.
Upvotes: 0
Views: 2789
Reputation: 1450
You can use:
- $(this).closest('tr');
OR
- $(this).parent().parent();
.closest() will give you closest tr to the button and .parent() will return parent element(td) and again it's parent will return that row
Upvotes: 1
Reputation: 41595
I would recommend you to use $(this).parent().parent()
for a better performance.
http://jsperf.com/parentparentvsclosest/2
But if you are looking for code simplicity, then you could go for $(this).closest('tr')
.
Upvotes: 1
Reputation: 148120
You can use closest() to get the parent tr of the button being clicked.
var trOfButton = $(this).closest('tr');
Description of closest: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree, Reference.
Upvotes: 2