Reputation: 135
while($row = mysqli_fetch_array($stmt)) {
output .= '<tr>
<td id=compare><button class=comparison>Search</button></td>
</tr>
<tr id=matching class=matching>
<td colspan=12>None of a data was found</td>
</tr>'
}
The above shows my php part and the code below shows my jquery process. What I want to do is that when I click on a/any button class=comparison
, it will shows the hide tr
which is class=matching
based on the row of table that have been choose or clicked. But the problem is that when I click on the button, it shows all of the tr
of the same class.
$(".comparison").on("click", function () {
if($(".matching").is(":hidden")) {
$(".matching").slideToggle("fast");
}
else {
$(".matching").hide();
}
});
How to select an appropriate class with the same class name in a php while loop?
Upvotes: 2
Views: 80
Reputation: 7039
Try using $(".matching", $(this))
instead of $(".matching")
everywhere. The second parameter specifies that you are looking for the matching class inside the current object.
You could also make a variable instead of typing it again and again like this:
var matching = $(".matching", $(this))
Upvotes: 1
Reputation: 133433
Problem is that you are targeting all elements when using $(".matching")
. You need to use the relationship between DOM elements and target the desired element.
As per current HTML, you can traverse up to tr
using .closest()
/.parents()
then find its immediately following sibling using .next()
$(".comparison").on("click", function () {
var matching = $(this).closest('tr').next('tr.matching');
if(matching.is(":hidden")) {
matching.slideToggle("fast");
}
else {
matching.hide();
}
});
Additionally, Identifiers in HTML must be unique, thus get rid of duplicate identifiers since you are not using them.
Upvotes: 5
Reputation: 93
Try This -
$(".comparison").on("click", function () {
var $matching = $(this).parent().next('.matching');
if($matching.is(":hidden")) {
$matching.slideToggle("fast");
} else {
$matching.hide();
}
});
Upvotes: 0