3

The following link should be disabled after the first click

<%= link_to "Submit Order", {:action => "charge"}, class: 'btn btn-primary', id: 'confirmButton' %>

The following code permanently disables the link:

ready = ->

$('#confirmButton').click (e) ->
  e.preventDefault()
  return

$(document).ready(ready)    
$(document).on('page:load', ready) 

How do I have to modify this code, so that the link is active on the first click and then disabled on subsequent clicks?

mr. jman
  • 121
  • 3
  • 15

5 Answers5

5

Consider using a button instead; rails' button helper supports a disabled_with data attribute that should automagically disable the button once it's been clicked.

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to-label-Data+attributes

This also works for the form submit helper

http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-submit_tag-label-Data+attributes

BM5k
  • 1,210
  • 10
  • 28
  • Thank you for your answer. This seems like the best solution using what's already built in under the hood. – mr. jman May 11 '16 at 14:14
3

You can add a disabled class to the button after the first click

$('#confimationButton').on('click', function() {
  if($(this).hasClass('disabled'))
    return;
  // do work
  $(this).addClass('disabled');
});
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
2
<%= link_to "Submit Order", {:action => "charge"}, class: 'btn btn-primary', id: 'confirmButton', data: { disable_with: "Please wait..." } %>
Boltz0r
  • 970
  • 5
  • 16
1

A slight variation to Antarr Byrd's answer

$('a').on('click', '.disabled', function(){
  return false;
});

and then add the disabled class like he mentioned

Community
  • 1
  • 1
BM5k
  • 1,210
  • 10
  • 28
0

Adding a class is fine if you want to change the display properties (color, etc) but doesn't actually disable the link. Apparently setting the 'disabled' property doesn't either. The solutions I've seen all have to do with setting the 'click' handler of the link to return false or stop propogation of the click action. This post is a good example:

disable a hyperlink using jQuery

Community
  • 1
  • 1
Fred Willmore
  • 4,386
  • 1
  • 27
  • 36