Reputation: 13
In the below code I have 3 buttons with content under each one. When I click a button it shows the content of all the buttons. I want to only show the content of the clicked button.
$(".item").click(function() {
$(".d-text").show();
});
.d-text {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="item item1">button</button>
<p class="d-text">Dummy text</p>
<button class="item item2">button</button>
<p class="d-text">Dummy text</p>
<button class="item item3">button</button>
<p class="d-text">Dummy text</p>
Upvotes: 0
Views: 63
Reputation: 4180
You need to add a specific class/id to each p item so you can link together a specific button with the right text
https://jsfiddle.net/zdyw8ra4/
HTML:
<button class="item item1"data-target="#item1">button</button>
<p class="d-text"id="item1">Dummy text1</p>
<button class="item item2"data-target="#item2">button</button>
<p class="d-text" id="item2">Dummy text2</p>
<button class="item item3" data-target="#item3">button</button>
<p class="d-text"id="item3">Dummy text3</p>
JS:
$(".item").click(function() {
$($(this).data('target')).toggle();
});
Upvotes: 0
Reputation: 27041
You have to use .next()
$(this).next(".d-text").show();
This will only show the next p
after the button your clicked.
Demo
$(".item").click(function() {
$(this).next(".d-text").show();
});
.d-text {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="item item1">button</button>
<p class="d-text">Dummy text</p>
<button class="item item2">button</button>
<p class="d-text">Dummy text</p>
<button class="item item3">button</button>
<p class="d-text">Dummy text</p>
Upvotes: 3