3

I'm trying to disable a button after a user clicks it. I have this functionality working great but now the form wont submit... Here is my javascript:

<script>
  $('.button').on('click', function(event) {
    $(this).prop('disabled', true);
  });
</script>

Again this disables the button nicely but now my form wont submit. Is this a well known problem?

1

3 Answers 3

5

Instead of putting it in the click handler, put it in the form's submit handler.

$('form').on('submit', function(event) {
  $(this).find(".button").prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <button class="button">Submit</button>
</form>

Sign up to request clarification or add additional context in comments.

3 Comments

This is cool but how can I still pass the button value params to the controller?
@Bitwise See Variant 1 of my answer
@Bitwise Looks like this has the same problem as Vitali's answer. I guess the timeout method is the only real solution.
3

Click event occurs before form submit and disabled button prevents submission. This is workaround:

<script>
  $('.button').on('click', function(event) {
    $this=$(this);
    setTimeout(function(){$this.prop('disabled', true);},50);
  });
</script>

Another workaround is to process $('form').on('submit',function(){...});

Edit: ...INSTEAD.

9 Comments

Not only does that sound weird, it seems to not be the case: jsfiddle.net/khrismuc/2zo6uev5
@ChrisG Your fiddle is disabling form submission by returning false from the event handler.
@Barmar ...yeah, but the onsubmit event is not cancelled at all. And if you remove the line or return false, the form submits just fine. Unless I'm completely off-track, disabling a button does not in any way prevent a form submission, and why on earth should it?
@ChrisG I'm not getting the alert in your fiddle.
@ChrisG alert in your fiddle doesn't appear ;(
|
0
<script>
  $('.button').on('click', function(event) {
    $(this).prop('disabled', true);
    $(this).parents('form').submit();
  });
</script>

5 Comments

This is pretty good, but the button value won't be included in the form parameters.
So change places of event lines. At first: $(this).parents('form').submit(); Then $(this).prop('disabled', true);
It doesn't matter where you place it. When you call submit() from code, it doesn't send any buttons. Buttons are only sent automatically when the submission is triggered directly from clicking a submit button.
You right. Add timeout to second event's line: setTimeout(function(){ $(this).prop('disabled', true); }, 100);
Or use <input type="submit"> instead of <button>Submit</button>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.