I have this HTML code:
<tr> <td><input type="checkbox" class="chk" /></td> <td><div class="disabled">text to hide 1</div></td> <td><div class="disabled">text to hide 2</div></td> </tr>
I'm using jQuery to hide all class="disabled"
items:
$("div.disabled").hide() ;
I want to show disabled divs when I click the checkbox in the same row (tr). I tried
$("input.chk").click(function(){ $(this).parent().parent().(".disabled").show(); }) ;
but it doesn't work.
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.
parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.
The parents() method returns all ancestor elements of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the parent element along ancestors of DOM elements, all the way up to the document's root element (<html>).
The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.
Use .closest()
and .find()
, like this:
$("input.chk").click(function(){ $(this).closest('tr').find(".disabled").show(); });
Your current code almost works, you need a .find()
though, like this:
$(this).parent().parent().find(".disabled").show();
If you have many rows like this, use .delegate()
, like this:
$("table").delegate("input.chk", "click", function(){ $(this).closest('tr').find(".disabled").show(); });
.delegate()
instead binds one handler to the table for all of the input.chk
elements to bubble up to. If you're looking to enable/disable, use change
and .toggle()
in addition to the above, like this:
$("table").delegate("input.chk", "change", function(){ $(this).closest('tr').find(".disabled").toggle(this.checked); });
This way if it's checked they show, if not they hide.
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