Jquery Find Active Class And Replace that class

173 views Asked by At

enter image description here

From the above image currently 1st View Details is clicked so it is showing as Hide Details.

if i click on 3 rd View Details all 1st one or(Active one) has to be relaced to view details how can i do that..?

Here what i have tried:

Hide Details:

$("#tbodyid" ).on( "click", ".hide-details", function() {
$("#participantsForGd").hide();
var field = $(this);
field.text("View Details");
field.addClass("view-details");
field.removeClass("hide-details");
});

View-datails

$("#tbodyid" ).on( "click", ".view-details", function() {
$("#participantsForGd").show();
var field = $(this);
field.text("Hide Details");
field.addClass("hide-details");
field.removeClass("view-details");
});

My html:

<?php while($grpData = $grpQuery->fetch_assoc()){ ?>
<tr>
<td>
<span id="<?php echo $grpData['group_id'];?>" class="view-details">View Details</span>
</td>
</tr>
<?php } ?>

This one has to work like toggle:

<form id="participantsForGd" >BLAH BLAH </form>
2

There are 2 answers

0
Mehedee On BEST ANSWER

Your html structure is not good to do this task easily. I am showing how you perform this task. Then you can modify as your need.

HTML:

<button class='details-btn hide-details'>Hide Details</button>
<button class='details-btn view-details'>View Details</button>
<button class='details-btn view-details'>View Details</button>
<button class='details-btn view-details'>View Details</button>

JQuery:

$('.details-btn').click(function(){
    $('.details-btn').each(function(){
        $(this).removeClass('hide-details').addClass('view-details').text('View Details');
    });
    $(this).removeClass('view-details').addClass('hide-details').text('Hide Details');
})
2
vanzand On

I think your php code will generate dom structure as below:

<table>
    <tbody id="tbodyid">
    <tr>
        <td id="group-id-1" class="details view-details">View Details</td>
        <td id="group-id-2" class="details view-details">View Details</td>
        <td id="group-id-3" class="details view-details">View Details</td>
        <td id="group-id-4" class="details view-details">View Details</td>
    </tr>
    </tbody>
</table>

And you have four divs which contains details for each button.

<div id="participantsForGd-1" class="participantsForGd"></div>
<div id="participantsForGd-2" class="participantsForGd"></div>
<div id="participantsForGd-3" class="participantsForGd"></div>
<div id="participantsForGd-4" class="participantsForGd"></div>

My solution is :

$('#tbodyid').on('click', '.details', function(){
    $('.details').each(function(){
        $(this).removeClass('hide-details').addClass('view-details').text('View Details');
    });
    $('.participantsForGd').each(function(){
        $(this).hide();
    });
    $(this).removeClass('view-details').addClass('hide-details').text('Hide Details');
    $('#participantsForGd-' + $(this).attr('id').split('-')[2]).show();
})