4fbluw
Last Updated: February 25, 2016
·
17.16K
· zepplock
2133a8acbe03c401ab8d51c9321274a7

Rails, Twitter Bootstrap and "Disabled" links/buttons

One interesting problem I was trying to solve today:

How do I disable a link generated by link_to in Rails (with Bootstrap). Here's a code in question:

= link_to edit_project_path(project), :class=>"btn btn-primary", :disabled => true do
              %i.icon-edit
              Edit

This turns a link into a Bootstrap-looking button and makes it look 'disabled' but it is still clickable!. Most people just switch to using button_to which will generate a form which is properly disabled by a browser.

There's one caveat about button_to though, you can't include HTML content into a button and I want my buttons to have icons (see that %i.icon-edit?)

So the solution is use unobtrusive JavaScript to make 'disabled' link non-clickable. For example add the following code to your application.js:

$(document).ready(function() {
    $('a[disabled=disabled]').click(function(event){
        event.preventDefault(); // Prevent link from following its href
    });
});

5 Responses
Add your response

5630
866166d85ad1af8b9ecefd6e40b50e79

Thanks!!!

over 1 year ago ·
6478
6e6b8499b2974b16f5cb4dfaf618563a

In your javascript if you return false; instead of having event.preventDefault(); it will stop any alerts or confirm messages that you have attached to the link via the rails data-confirm method.

over 1 year ago ·
13635
3d2ac2e3d429f4ffda6f871762850007

Using disabled: true works in my .erb Rails code, e.g:

<%= link_to "Button Title", link_path, data: { confirm: 'Confirm Request' }, class: "btn btn-warning btn-sm", disabled: true %>

over 1 year ago ·
15619
6e12977acc1600c0f367d6d7b9265f95

As bayendor points out, this is already supported using Rails UJS. You can either disable links through the link helper by setting disabled: true, or on standard links by setting disabled="disabled" on the <a> element.

over 1 year ago ·
26713
None

Actually, Bootstrap does look for the "disabled" class and/or "attribute" on links! See http://getbootstrap.com/css/#anchor-element-1. Maybe you forgot to require "bootstrap" in your application.js file (or maybe something changed in the meantime)?

And RE lightswitch05, Rails UJS supports the "data-disable-with" attribute on links, which changes the text of the link after it is clicked, but does not support the "disabled" attribute (or at least it does not anymore). See http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to.

Just thought I would chime in as it took me a bit to track down the correct answer!

over 1 year ago ·