Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

I use this method:

$(document).ready(function() {
  $('.auto-submit-disable')
    .submit(function () {
      $(this).find('button,input[type=submit]')
        .attr('disabled', 'true');
    });
});

if ($('.auto-submit-disable'))
  window.onunload = function(){}; // This forces re-execution of js

After that, just put class="auto-submit-disable" on your forms. Notice that the method is heavy to browsers, because repeating all JS upon back-navigation is heavy.

So it's not recommended as a general method to run on all your pages!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top