George Johnston
George Johnston

Reputation: 32258

jQuery Event only firing for first named element

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?

Upvotes: 3

Views: 368

Answers (4)

David
David

Reputation: 1927

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) { 

Upvotes: 1

Sampson
Sampson

Reputation: 268364

$(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'
  });
});

Upvotes: 5

jessegavin
jessegavin

Reputation: 75650

You should change them to a class.

Read this.

Upvotes: 2

Pointy
Pointy

Reputation: 413737

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>

Upvotes: 7

Related Questions