I've got a table with multiple rows. In each row is a Show Details Button and a Hide Details button. On clicking show details I want the hide details button to only show for the specific row. I thought the .closest() function would work but it hasn't yet.
Here is the HTML
<table>
<tr id="1">
<td><button class='view'>View Details</button><button class='hide' style='display:none;'>Hide Details</button></td>
</tr>
<tr id="2">
<td><button class='view'>View Details</button><button class='hide' style='display:none;'>Hide Details</button></td>
</tr>
</table>
Here is the jQuery
$(".view").click(function() {
$("#patient").show("");
$(this).hide();
$(this).closest(".hide").show();
});
jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.
The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.
jQuery parent() Method The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree.
The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
.closest
looks at the current element and its parents only. You'd have to do this like:
$(this).parent().find('.hide');
or
$(this).siblings('.hide');
Are you binding after the dom is ready? Try this:
$(function(){
$(".view").click(function() {
$("#patient").show("");
$(this).hide().next().show();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With