wcdomy
wcdomy

Reputation: 215

.toggle() function

I want to apply the toggle function to the two buttons separately. However, when I use the code below, it toggles both content under each button. How can I separate them so that when I click the first button only the content under it will be toggled?

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>

<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>

<script>
$("button").click(function () {
$("p").toggle();
});
</script>

</body>
</html>

Upvotes: 1

Views: 801

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

Simple: use nextUntil().
Will select all the next elements until matched element reached (in your case the next button):

jsFiddle demo

$("button").click(function () {
     $(this).nextUntil('button').toggle();
});

Upvotes: 2

j08691
j08691

Reputation: 207901

Why have two paragraph tags for this? Make your HTML:

<button>Toggle</button>
<p>Hello</p>

<button>Toggle</button>
<p>Hello</p>

and your jQuery:

$("button").click(function () {
    $(this).next('p').html( ($(this).next('p').html()=='Hello')?'Good Bye':'Hello');
});​

jsFiddle example

Upvotes: 0

Chandu
Chandu

Reputation: 82903

Try this:

$("button").click(function () {
  $(this).nextAll("p:lt(2)").toggle();
});

http://jsbin.com/orujav

Upvotes: 1

Related Questions