Thursday, 30 August 2018

How to select an appropriate class with the same class name in a php while loop

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?

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.

0 comments:

Post a Comment