Last Updated: February 25, 2016
· zepplock

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

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() {
        event.preventDefault(); // Prevent link from following its href

5 Responses
Add your response



over 1 year ago ·

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 ·

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 ·

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 ·

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 ·