Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery parent().("selector")

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.

like image 478
el_quick Avatar asked Sep 30 '10 18:09

el_quick


People also ask

How do I find a specific parent in jQuery?

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.

What is the difference between parent () and parents () methods in jQuery?

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.

What is jQuery parent?

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>).

What does $( Div parent will select?

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.


1 Answers

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.

like image 150
Nick Craver Avatar answered Oct 03 '22 12:10

Nick Craver