views:

56

answers:

3

For some strange reason, whenever I have a selector and expect to get multiple items, jQuery is only returning the first item, instead of the entire collection.

This is the HTML I have:

<a id="reply-424880" class="reply" href="#" rel="nofollow">Reply</a>
<a id="reply-424885" class="reply" href="#" rel="nofollow">Reply</a>

And the selector:

$('.reply').unbind('click').click(function(event) {
 ...
}

I have tried debugging using FireBug, and still get the same results. Using the work around I can get it to work:

$('a').each(function (index, element) {
            if ($(element).attr('class') == 'reply') {
                $(this).unbind('click').click(function(event) {
                     ...
                });
             }
});

I would like to use the built-in functionality instead of my work around. Any idea why only the first element would be returned?

A: 

That should work but what about ...

$('.reply').each(function() { 
   $(this).unbind('click').click(function(event) {
      ... 
   });
});
gmcalab
+2  A: 

What you have should be working already, you can see an example here, this is a simple call:

$('.reply').unbind('click').click(function(event) {
  alert('hi there');
});​

You must have something outside the question affecting your links if the same handler's not being executed for all of them. If you're getting an attribute from the first only, make sure inside your function you're not doing something like $(".reply").attr("id"), you should be using this inside the handler, of you'll get the attribute from the first element matched.

Here's an example:

$('.reply').unbind('click').click(function(event) {
  alert($('.reply').attr("id")); //alerts "reply-424880" for both
});​

It should be like this:

$('.reply').unbind('click').click(function(event) {
  alert($(this).attr("id")); //alerts "reply-424880" for both
  //and use just this.id in this case, no need for jQuery .attr(), like this
  //alert(this.id);
});​
Nick Craver
Yea I don't see where they could be going wrong... Definitely a simple call. +1
gmcalab
A: 

After leaving the workaround in place for a couple of months, I decided to try to see if there was anything on the page that was causing the problem.

By process of elimination, I was able to narrow down the error to the jquery.validate.js file. For some unknown reason, this file was causing the jQuery to only return the first value. I downloaded the latest version and the selectors now return all the elements that match.

Andy