Disable HTML button after clicking to prevent double-click

at. picture at. · Jun 10, 2013 · Viewed 11.6k times · Source

I want to prevent double-clicks, so setting the disabled attribute on the input element upon a click event seems like the right thing to do. And other stackoverflow answers reflect that. So this is what I wrote in CoffeeScript with jQuery:

$('input[type="submit"]').on('click', ->
  $(this).addClass('disabled').attr('disabled', 'disabled')
  $(this).val('Sending')
)

I have addClass('disabled') for Foundation.

Generally this works. However, if I click back, the button is still disabled. If I go to the page and the page was cached, the button is still disabled. Is there a JavaScript library that deals with all these little issues? Seems like this is a very common need. Is there just a little bit more JavaScript/jQuery I need to add to the above?

I would've thought HTML5 would have some mechanism for this by now.

UPDATE: I tried to listen for pageshow events and un-disable submit buttons:

$('input[type="submit"]').on('pageshow', function() {
  console.log('pageshowed')
  $(this).removeClass('disabled').removeAttr('disabled').val('Submit');
});

Nothing happens though, not even when the page is first loaded. Am I using pageshow wrong?

Answer

robertc picture robertc · Jun 11, 2013

Use the pageshow event on the window object. Works in Chrome and Safari as well as Firefox, not sure about IE, doesn't work on Opera 12 (but will work in Opera 15, since same engine as Chrome). Try typeof window.onpageshow in console to detect.