views:

57

answers:

4

I have hyperlinks, all are named 'mylink'. They should all fire the same event, but only the first element named 'mylink' actually fires. My code is as follows:

 $(document).ready(function() { 
        $("#formID").validationEngine() 
        $('#mylink').click(function(e){ 
           var goto = $(this).attr('href'); //get the url 
           $.ajax({ 
              url: goto 
           }); //execute the href 
           e.preventDefault(); //prevent click
           $('#mylink').parent().parent().fadeOut("slow");
        }); 
    })

Where am I going wrong?

+5  A: 

You can't re-use an "id" value. A given "id" can only be used once on a page.

If you need multiple elements to be affected, use a "class" component:

<div id="uniqueString" class="makeMeMoo makeMePurple makeMeClickable">
  <!-- whatever -->
</div>
Pointy
+2  A: 

You should change them to a class.

Read this.

jessegavin
As in, <a href="/" class="id">Link</a> ?
George
No, as in <a href="/" class="someClass">Link</a>
Davide Gualano
+3  A: 
$(function(){
  $("#formID").validationEngine(); // don't forget your semi-colons
  $(".mylink").click(function(e){  // ID's should be unique, use classes instead
    e.preventDefault();
    $.ajax({ url: $(this).attr("href") });
    $(this).parent().parent().fadeOut("slow"); // refer to this as 'this'
  });
});
Jonathan Sampson
Perfect, thanks.
George
@GeorgeJohnston: Remember that `id='foo'` should only appear on a page once. But `class='foo'` can appear many times. So you can only have one `<a id='foo'>` but many `<a class='foo'>`. Best of luck!
Jonathan Sampson
A: 

I don't know that it's all that much more efficient, but while your in there, it might not be a bad idea to reference that link by element (a#mylink) also, otherwise jquery could have to search the entire document for the class.

 $('a#mylink').click(function(e) { 
David