Code is not running .click hyperlink

The code doesn't work for .click if I have:

$(".cancel").click(function() {
    alert("got here");
    $(this).closest(":dialog").dialog("close");                            
});

<a class="cancel" href=""><img src="images/cancelButton.gif" border="0" /></a>

      

It must be something silly, but I don't see it.

+2


a source to share


5 answers


I would suggest that you are wrapping the code in $(document).ready( function () { ... });

?



$(document).ready( function () {
  $('.cancel').click( function(e) {
     alert('here!');
     e.preventDefault(); // prevents click from following through
  });
});

      

+7


a source


add return false at the end of the click event:



$(".cancel").click(function() {
    alert("got here");
    $(this).closest(":dialog").dialog("close");
    return false;                            
});

      

+1


a source


If href=""

instead href="#"

does not mean that it actually reloads the page on a button click?

0


a source


Anyway, when you add an onclick event with a javascript call, if you add return false, the default behavior (which would be without the onclick event) will be ignored.

And so in this case, return return false will prevent the browser from navigating to the link anchor.

Edit

Fair comment below - looked at jquery.com and it says

Returning false from a handler is equivalent to calling both .preventDefault () and .stopPropagation () on the event object.

0


a source


Several people said to add return false; to your click handler. Instead, you should use the preventDefault method on the event class like this:

$(".cancel").click(function(event) {
  event.preventDefault();
  alert("got here");
  $(this).closest(":dialog").dialog("close");
});

      

Make sure you pass the event to the handler function. This is the preferred jQuery way. I also always put preventDefault()

as the first in the handler method, but I don't think it matters.

0


a source







All Articles