2

I'm using jQuery to disable hyperlinks if the user isn't allowed to click on them.

The documentation(http://api.jquery.com/attr/) says:

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

I assume form elements are <input ...> elements so not links (<a>)

And that's why .prop('disabled', true) doesn't work, while .attr('disabled', 'disabled') does. However, is it supposed to work? Is there a specification which say that links can be disabled, in which case clicking on them won't have any action? - or is it just something few browsers implement because they're being nice?

If disabled isn't actually meant to be on links, is there any other easy way to forbid the user clicking on the link, or should I just remove and reattach the href attribute?

peter
  • 14,348
  • 9
  • 62
  • 96
  • Better remove and reattach die href-element. Its the cleanest way of giving or restricting access to links I guess. Every other way still makes the link-url still accessable, leading to inconsistencies in your app. – Ahab Feb 25 '15 at 11:06
  • I posted an answer to a similar question which also includes Bootstrap a few years back: http://stackoverflow.com/a/16788240/1317805 – James Donnelly Feb 25 '15 at 11:19

2 Answers2

4

According to the specification at the MDN there is no attribute disabled allowed.

If you want a user to prevent clicking the link you can do it in serveral ways:

$('a').on('click', function(event){
    event.preventDefault(); //prevent the default behaviour of the Link (e.g. redirecting to another page)
});

Or

$('a').removeAttr('href'); //The link is not clickable anymore

Whereas the first Option will leave the link as it is, the second option will change the look of the link, as you can see in the demo. When using the second option you could save the origin-href to be able to re-attach it later.

Demo

empiric
  • 7,825
  • 7
  • 37
  • 48
2

As you've found, the disabled is for form inputs and is not valid for use on a elements.

Instead you could use preventDefault() within the click handler of the a elements to stop their behaviour:

$('a').click(function(e) {
    if (clicksAllowedFlag) {
        // your logic here...
    }
    else {
        e.preventDefault();
    }
});

Or, if you want to stop the link working only without performing any custom logic:

$('a').click(function(e) {
    !clicksAllowedFlag && e.preventDefault();
});

In cases when the flag is set to false you may want to consider styling the UI so that it is obvious the link is disabled, otherwise your users may be confused as to why clicking a link is having no effect.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339