Muhammad Hafiz Hussin Muhammad Hafiz Hussin - 5 months ago 16
Javascript Question

Show/Hide <p> in multiple <div>

I need your help. I am doing a page in which displaying management profiles. Each management will be display in a single div tag. If in database have 6 peoples, it will display 6 divs tag.

What I am trying to do is to do show/hide for p tag in every div declared. Each div declared using perl programming using FOREACH. Here is my code as below:-

[% FOREACH management = ir.var.ir_Directors.management.format.directors %]
[% NEXT IF management.remarks == 'new' %]
<div class="full_box ">
<div class="box_content si_fixed">
<div class="info full">
<div class="bod_left"><div class="bod_img">[% IF management.url_image %]<img src="[% management.url_image %]" class="ir_left management_img" alt="[% management.name %]" />[% END %]</div></div>
<div class="bod_right"><div class="bod_name_design"><h4 class="ir_textMainHighlight">[% management.name %]</h4><br/><div class="bod_designation">[% management.designation %]</div></div>
<div class="bod_remark">[% management.remarks %]</div>
<div class="bod_desc"><a class="button" href="#">View Profile</a><br/>
<p>[% management.description %]</p></div>
</div>
</div>
<div class="clear"></div>
</div>
<div class="box_bottom"></div>
</div>
[% END %]
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.bod_desc p').addClass('hide');

$('a.button').click(function(){
$(this).children('.bod_desc p').toggleClass('hide');
return false;
});
});
</script>


Referring to above codes, whenever user click at link with class "button"; inside div class "bod_desc", it will display the "management.description" text inside the p tag. However, when it display in the browser, everything look okay except when I click the "View Profile" link. It wont display the "hide" p tag. Your help are much appreciated. Thanks!

Answer

<p>s are not children of <a>, they are siblings; so .children() won't work.

Use,

$('a.button').click(function(){
    $(this).siblings('p').toggleClass('hide');
    return false;
});

or

$('a.button').click(function(){
    $('p',$(this).closest('.bod_desc')).toggleClass('hide');
    return false;
});
Comments