Reputation: 3
First I'd like to apologize because my code layout isn't the best. What I'm trying to accomplish here is to display a description of a text sample by pressing an info button. My problem is when I press any of the info buttons, it displays all the descriptions of all text samples, when it should show only the description of the intended text sample at each time.
I appreciate your help. Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("dd").hide();
$(".btn1").click(function() {
$("dd").toggle("slow");
});
$("dd").hide();
$(".btn2").click(function() {
$("dd").toggle("slow");
});
$("dd").hide();
$(".btn3").click(function() {
$("dd").toggle("slow");
});
});
</script>
</head>
<body>
<dl>
<dt>Coffee</dt>
<button class="btn1">+ Info</button>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<button class="btn2">+ Info</button>
<dd>White cold drink</dd>
<dt>Water</dt>
<button class="btn3">+ Info</button>
<dd>Transparent fluid</dd>
</dl>
</body>
</html>
Upvotes: 0
Views: 84
Reputation: 448
Change your html into the following adding IDs to the dd :
<body>
<dl>
<dt>Coffee</dt>
<button class="btn1">+ Info</button>
<dd id="dd1">Black hot drink</dd>
<dt>Milk</dt>
<button class="btn2">+ Info</button>
<dd id="dd2">White cold drink</dd>
<dt>Water</dt>
<button class="btn3">+ Info</button>
<dd id="dd3">Transparent fluid</dd>
</dl>
</body>
Then in your jquery script :
$(document).ready(function() {
$("dd").hide();
$(".btn1").click(function() {
$("#dd1").toggle("slow");
});
$("dd").hide();
$(".btn2").click(function() {
$("#dd2").toggle("slow");
});
$("dd").hide();
$(".btn3").click(function() {
$("#dd3").toggle("slow");
});
});
Here is the JSFiddle
EDIT :
Here is a shorter version of the above code achieving the same result in less code lines:
$(document).ready(function() {
$("dd").hide();
$("dl button").click(function() {
$("dd").hide();
var number = $(this).attr('class').substr(-1);
$("#dd"+number).toggle("slow");
});
});
Upvotes: 0
Reputation: 64657
Change
$(".btn1").click(function(){
$("dd").toggle("slow");
});
To
$("button").click(function(){
$(this).next('dd').toggle("slow");
});
Because you need to select not ALL dd elements, but only the ones that are next to the button that was clicked.
Upvotes: 3