1

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>
0

3 Answers 3

2

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();
});
Sign up to request clarification or add additional context in comments.

7 Comments

Awesome! Works! What is the .nextUntil thing?
@wcdomy as I said, it will collect all the elements he founds (in our case the <p> elements) until selector reached ('button'). api.jquery.com/nextuntil but not including the selector we mention (the next <button>), ideal to use in your case!
If I want to change the text for the button once it's clicked. For example, from "Edit" to "Save". How can I do that? @Roko C. Buljan
Sure you can: jsbin.com/eroyas/3/edit Please, take in consideration to accept an answer! meta.stackexchange.com/questions/5234/…
@wcdomy You can also use ternary operators to check / change text: jsbin.com/eroyas/4/edit
|
1

Try this:

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

http://jsbin.com/orujav

1 Comment

If I want to change the text for the button once it's clicked. For example, from "Edit" to "Save". How can I do that?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.