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
});
});
Written by Vladimir Reshetnikov
Related protips
6 Responses
Thanks!!!
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.
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 %>
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.
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!
I figured out another way to do this without the JavaScript. The JavaScript also works but it is MUCH easier to just put for example.
<%= link_to "Button Title", "#", data: { confirm: 'Confirm Request' }, class: "btn btn-warning btn-sm", disabled: true %>
Notice I took out the link_path and put in "#" which tells it to go no place at all. Worked for me. :)