views:

233

answers:

2

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?

+19  A: 

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
and if you have CSS definitions for the id of 'violacao', please adjust accordingly
Dan Appleyard
Thanks! Now it's working.
Ricardo
Good point Dan! Glad it's working Ricardo
spmason
+1  A: 

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
Thanks for the information SebaGR!
Ricardo
Wick
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
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
@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
Wick