AlexB AlexB - 7 hours ago 2
Javascript Question

Show/Hide jQuery, shows all of the divs instead of one that was clicked

I am trying to use jQuery show

div
, but the problem I have is that it all of the
divs
with same class are being shown instead of the one that was clicked.

So basically, once
VIEW MORE
is clicked, the
div
should be visible and VIEW MORE should be hidden, then if the
VIEW MORE
in another
div
is clicked, same thing should happen in that
div
too.



$('.show-more').click(function() {
$('.text-hidden').show();
$(this).hide()
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="forms">
<h2>New Forms</h2>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>

<div class="forms">
<h2>Old Forms</h2>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>





I am not a big pro on jquery/javascript so please bear with me on this one.

Thanks

Answer

Use .next() to achive what you want

$(this).next(".text-hidden").show()

This will select the next element with the class text-hidden and show it

Example below.

$('.show-more').click(function(){
    $(this).next(".text-hidden").show();
    $(this).hide()
});
.text-hidden{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="forms">
<h2>New Forms</h2>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>

<div class="forms">
<h2>Old Forms</h2>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>