jQuery: get parent tr for selected radio button
Solution 1:
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Solution 2:
Answer
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
How to find the closest row?
Using .closest()
:
var $row = $(this).closest("tr");
Using .parent()
:
Check this .parent()
method. This is alternative of a .prev()
and .next()
.
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
Get All Table Cell <td>
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
VIEW DEMO
Get Only Specific <td>
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
VIEW DEMO
Useful methods
-
.closest()
- get the first element that matches the selector -
.parent()
- get the parent of each element in the current set of matched elements -
.parents()
- get the ancestors of each element in the current set of matched elements -
.children()
- get the children of each element in the set of matched elements -
.siblings()
- get the siblings of each element in the set of matched elements -
.find()
- get the descendants of each element in the current set of matched elements -
.next()
- get the immediately following sibling of each element in the set of matched elements -
.prev()
- get the immediately preceding sibling of each element in the set of matched elements