8

I want to disable the link during loading, for the code given below

<span id="addlink">"<%= f.add_associated_link('Add Task', @project.tasks.build, :class=>"add") %></span>

I tried it with the codes below but it didn't work

$("#addlink").attr("disabled", "disabled"); 

and

$("a.add").hide();
THelper
  • 15,333
  • 6
  • 64
  • 104
  • Could you provide some example code please. Like the link it produced. – Tyler Carter Jul 23 '09 at 04:36
  • possible duplicate of [how to enable or disable anchor tag using jquery ](http://stackoverflow.com/questions/1164635/how-to-enable-or-disable-anchor-tag-using-jquery) – Alex Angas Nov 11 '10 at 03:15

3 Answers3

27
function disableLink(e) {
    // cancels the event
    e.preventDefault();

    return false;
}

When you want to disable it yo call

$('#addlink').bind('click', disableLink);

When you want to enable disabled link you call

$('#addlink').unbind('click', disableLink);
RaYell
  • 69,610
  • 20
  • 126
  • 152
4
$('#addlink').click(function(e) {
    e.preventDefault();
    //do other stuff when a click happens
});

return false;

will prevent the default event from occuring and and also prevent the event from bubbling up

So chosing between these two depends on your use. If you want to stop the default action and also need to bubble up the event then use preventDefault

rahul
  • 184,426
  • 49
  • 232
  • 263
  • If you define it like that you cannot unbind it easily if you wan't to restore default behavior later. – RaYell Jul 23 '09 at 04:45
2

I'd go with a hybrid of RaYell's and phoenix's solution, adding jQuery's namespacing to the mix:

$('#addlink').bind('click.killlink',function(event){
    event.preventDefault();
    // You can do any additional onClick behavior here
});

To unbind this event, as well as any other related events (of any type) that you group with the .killink namespace, you'd run this:

$('#addlink').unbind('.killlink');

As phoenix pointed out, using return false will prevent the event from bubbling up. preventDefault() has the added benefit of being extremely explicit (unlike return false, which can mean many different things depending on the context).