Simplest way to disable button on submission of a form?

前端 未结 5 1973
执念已碎
执念已碎 2020-12-15 04:10

I\'ve been trying to find the \"right\" way to prevent double submits of forms. There are lots of related posts on SO but none of them hit the spot for me. Two questions b

相关标签:
5条回答
  • 2020-12-15 04:39

    You could try using the following code:

    $(document).ready(function(){
       $(".once-only").click(function(){
          this.submit();
          this.disabled = true;
          return true;
       });
    });
    
    0 讨论(0)
  • 2020-12-15 04:46

    You can use jQuery's submit(). In this case, it should look something like this:

    $('form').submit(function(){
        $(this).children('input[type=submit]').prop('disabled', true);
    });
    

    Here is a working jsFiddle (made by Mike) - http://jsfiddle.net/gKFLG/1/.

    If your submit-button is not a direct child of the form-element you will need to replace children with find. Additionally, your submit-button may also be a button element instead of an input element. E.g. This is the case if you are using Bootstrap horizontal forms. Below is a different version of the snippet:

    $('form').submit(function(){
        $(this).find('button[type=submit]').prop('disabled', true);
    });
    

    Demo jsFiddle - http://jsfiddle.net/devillers/fr7gmbcy/

    0 讨论(0)
  • 2020-12-15 04:53

    Similarly Ive seen a few examples, this one allows you to alter how long the button is disabled for, through timeout. It also only triggers on a form submit rather than on the buttons click event, which originally caused me a few issues.

        $('form').submit(function () {
            var button = $('#button');
            var oldValue = button.value;
            var isDisabled = true;
    
            button.attr('disabled', isDisabled);
    
            setTimeout(function () {
                button.value = oldValue;
                button.attr('disabled', !isDisabled);
            }, 3000)
        });
    
    0 讨论(0)
  • 2020-12-15 04:56

    Simple and effective solution is

    <form ... onsubmit="myButton.disabled = true; return true;">
        ...
        <input type="submit" name="myButton" value="Submit">
    </form>
    

    Source: here

    0 讨论(0)
  • 2020-12-15 05:00

    This should help:

    <form class="form-once-only" method="POST">
        <input type="text" name="q"/>
        <button type="submit" class="once-only">Send</button>
    </form>
    

    Javascript:

    $(document).ready(function(){
        $("form.form-once-only").submit(function () {
            $(this).find(':button').prop('disabled', true);
        });
    }
    
    0 讨论(0)
提交回复
热议问题