View Full Version : jQuery each() not working out for me

10-23-2009, 02:33 PM
I've been at this on and off for a week but it never seems to work quite right.

Basically I have multiple divs that are hidden preceded by a button before each one but it has to start hidden on load. All I want is any of the buttons to only open the div directly after it. At the moment it seems to want to open all of them.

Here is the snippet of code:

<div class="buttonClass"><button class="ForumButton" type="button">Click to open</button></div><div class="forumPaster">Hidden information</div>

Here's what I have so far:

$(document).ready(function() {
$(".ForumPasteButton:button").bind('click', function() {

Nothing. It still wants all of them. I can't seem to find anything that says only the next one only.

10-23-2009, 03:00 PM
The each() function applies the request to each matched item. So, in your case, it's going to do just what you're getting: apply a toggle to each item of class forumPaster - that's all of them. Just what it says.

To further confuse the issue, you're binding the click function on every button to do the same thing. So you're doubly telling it to annoy and confound you to no end. :D

I'm far from a jquery pro, so with the little knowledge that I do have, I'd try a couple of things. First, if your layout implies a parent/child/sibling structure between the buttons and their supposed associated divs, use jquery selectors (http://docs.jquery.com/Selectors) to narrow down the toggle action.

If the layout doesn't allow for non-trivial traversal like that, though, you could do it easily by applying IDs to every element and setting up your button/click/toggle combo for each ID. More code, but easy to target exactly what you want.