CCR CCR - 3 months ago 10
HTML Question

Hide/ show the div element of same class name when a button is clicked

Here, i want to hide or show box2 and box3 when i click the button which is inside box1. Also the class box is repeated number of time dynamically. So whenever i click on the button it has to hide/show the class box2 and box3 associated to that particular class box only but rather it shows the box2 and box3 element from all the class. Please help me. Also it would be better if you could solve this problem using this keyword. Thank you. Below is my html and jquery code.



$(document).ready(function() {
$(".box2").hide();
$(".box3").hide();

$('.see').click(function() {
var value = $(this).attr('value');
$('.box2').toggle('fast');
$('.box3').toggle('fast');

if (value == 'See More') {
$(this).attr('value', 'See Less');
} else if (value == 'See Less') {
$(this).attr('value', 'See More');
}

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="Box">
<div class="box1">
<input type="button" class="see" value="See More" />
</div>
<div class="box2">
</div>
<hr />
<div class="box3">
</div>
</div>




Answer

Use $(this).closest(".Box") to find the box that contains the clicked button. From there you can find .box2 and .box3 in the same box.

Also, use .val() to get and set the value of an element.

$(document).ready(function() {
  $(".box2, .box3").hide();

  $('.see').click(function() {
    $(this).closest(".Box").find(".box2, .box3").toggle('fast');
    $(this).val(function(i, value) {
      return value == 'See More' ? 'See Less' : 'See More';
    });

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="Box">
  <div class="box1">
    <input type="button" class="see" value="See More" />
  </div>
  <div class="box2">
    Box 2
  </div>

  <hr />
  <div class="box3">
    Box 3
  </div>
</div>

<hr style="height: 2px; border: none; background-color: #000;">

<div class="Box">
  <div class="box1">
    <input type="button" class="see" value="See More" />
  </div>
  <div class="box2">
    Box 2
  </div>

  <hr />
  <div class="box3">
    Box 3
  </div>
</div>

Comments