Reputation: 25
I am new to jQuery and have run into a problem. I have a form that uses php to query a database, then display the result. My idea is to have only a portion of the returned row displayed with a button to display the remaining portions of the returned row. The problem is that when the button is clicked, it the displays the additional fields, but for all results rather than the selected result.
My html:
<div id="DocumentResults">
<!-- foreach($documents as $document) : -->
<div class="Document">
<div class="DocumentName"><strong>Product Name</strong></div><!-- end .DocumentName -->
<div class="DocumentActions">
<ul>
<li><a class="button_link toggle" href="#"><span>Details</span></a></li>
<li><a class="button_link" href="" target="_blank"><span>View</span></a></li>
</ul>
<div class="clear"></div>
</div><!-- end .DocumentActions -->
<div class="clear"></div>
<div class="DocumentDetails">
<ul>
<li>Manufacturer: </li>
<li>Product Number(s): </li>
</ul>
<div class="clear"></div>
</div><!-- end .DocumentDetails -->
</div>
<?php endforeach; ?>
And the jQuery
$(document).ready(function() {
jQuery(".DocumentDetails").hide();
// works but shows details for ALL results.
jQuery('.toggle').toggle(
function () {$('.DocumentDetails').animate({opacity:'toggle'}, 500);},
function () {$('.DocumentDetails').animate({opacity:'toggle'}, 500);}
);
});
I would be very greatful if someone could help me with this.
Upvotes: 0
Views: 461
Reputation: 22007
You should find the right ancestor of you button, and limit the selector to its descendant:
jQuery('.toggle').toggle(
function () {
$(this)
.parent().parent().parent().parent()
.find('.DocumentDetails').animate({opacity:'toggle'}, 500);
},
function () {
$(this)
.parent().parent().parent().parent()
.find('.DocumentDetails').animate({opacity:'toggle'}, 500);
}
);
Upvotes: 0
Reputation: 92903
By animating $('.DocumentDetails')
, you're targeting all instances of that class. Instead, use the this
variable (and some DOM traversal) to target only the results being clicked:
jQuery('.toggle').toggle(
function () {$(this).closest('.Document').find('.DocumentDetails').animate({opacity:'toggle'}, 500);},
function () {$(this).closest('.Document').find('.DocumentDetails').animate({opacity:'toggle'}, 500);}
);
Upvotes: 1