Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top