Question

Consider the following code:

$("a").attr("disabled", "disabled");

In IE and FF, this will make anchors unclickable, but in WebKit based browsers (Google Chrome and Safari) this does nothing. The nice thing about the disabled attribute is that it is easily removed and does not effect the href and onclick attributes.

Do you have any suggestions on how to get the desired result. Answers must be:

  • Easily be revertable, since I want to disable form input controls while I have an AJAX call running.
  • Must work in IE, FF, and WebKit
Was it helpful?

Solution

I assume that you have an onclick event handler bound to these anchor elements. Just have your event handler check the "disabled" attribute and cancel the event if it is set. Your event handler would look something like this:

$("a").click(function(event){
  if (this.disabled) {
    event.preventDefault();
  } else {
    // make your AJAX call or whatever else you want
  }
});

You can also set a stylesheet rule to change the cursor.

a[disabled=disabled] { cursor: wait; }

Edit - simplified the "disabled" check as suggested in comments.

OTHER TIPS

I had to fix this behavior in a site with a lot of anchors that were being enabled/disabled with this attribute according to other conditions, etc. Maybe not ideal, but in a situation like that, if you prefer not to fix each anchor's code individually, this will do the trick for all the anchors:

$('a').each(function () {
    $(this).click(function (e) {
        if ($(this).attr('disabled')) {
            e.preventDefault();
            e.stopImmediatePropagation();
        }
    });
    var events = $._data ? $._data(this, 'events') : $(this).data('events');
    events.click.splice(0, 0, events.click.pop());
});

And:

a[disabled] {
    color: gray;
    text-decoration: none;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top