1

I want to add the click event to all elements where the `id="violacao":

$(document).ready(function () {
    jQuery('#violacao').click(function() {
        alert('teste');
    });
});

But just the first link responds to the click. This is the HTML generated:

<tr>
  <td><a href="#" id="violacao">40954589</a></td>
  <td>Perda de Comunicação</td>
</tr>

<tr>
  <td><a href="#" id="violacao">88692020503</a></td>
  <td>Perda de Comunicação</td>
</tr>

When I try this way:

jQuery("a").click(function() {
    alert('teste');
});

It works fine, except that all links are affected. What is wrong?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Ricardo
  • 291
  • 2
  • 11

2 Answers2

19

IDs in HTML are meant to be unique (one per document). Change the ID to a class (and use . instead of #) and it should work.

spmason
  • 4,048
  • 2
  • 24
  • 19
1

While what Steve Mason says it's true, the actual problem is not that.

If you change ID to a class a problem persists: all links will get affected.

Instead, if you aim to affect one single <A>, you should do one of the following:

a) Assign unique IDs to each <A>, then do something like you were doing first; or

b) Assign classes and use the :first selector:

jQuery("a.violacao:first").click( function (){
  alert('teste');
} );

That will apply to the first matching anchor with class violacao. Alternatively, if you want to affect a specific anchor, you could use :eq(index).

For a comprehensive list of selector, visit http://docs.jquery.com/Selectors.

Seb
  • 24,920
  • 5
  • 67
  • 85
  • SebaGR misread the question, I think. Selecting one link is not what the poster wanted, rather it was part of the problem. The class solution is correct in this case, & doesn't select all links. Just wanted to clear that up. – Wick Mar 11 '09 at 18:40
  • I don't think so... he said "It works fine, except that all links are affected.", so I believe that "except" word tells us the desired behavior is to select just one anchor. – Seb Mar 11 '09 at 22:32
  • The "It works fine, except that all links are affected." comment was after the example where he tries the $('a').click(...) method, obviously this will affect all links. The actual problem was in the first example, which is down to duplicate IDs. – spmason Mar 12 '09 at 18:39
  • @Steve: if he changes IDs for classes the same behavior stays... All links will trigger. I bet what he actually did to solve it is assign different IDs as you suggested, which works fine. And that's the point I'm making: changing to == classes doen't solve it; assigning unique IDs does. – Seb Mar 12 '09 at 19:13
  • SebaGR: I suggest if you care to discuss this further, go back & read the original question carefully. The desired behavior was to select multiple links that contain a certain identifier - first sentence of the question. Using & selecting by class is the perfect solution, in this case. – Wick Mar 13 '09 at 12:11