Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

javascript - Simplest way to disable button on submission of a form?

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 below.

Here is my form

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

Here is my first attempt to disable double submits:

$(document).ready(function(){
    $(".once-only").click(function(){
        this.disabled = true;
        return true;
    });
});

This is the approach suggested here: Disable button after post using JS/Jquery. That post suggests the submitting element must be an input rather than a button, but testing both makes no difference. You can try it yourself using this fiddle: http://jsfiddle.net/uT3hP/

As you can see, this disables the button, but also prevents submission of the form. In cases where the submitting element is a button and an input element.

Question 1: why does this click handler stop submission of the form?

Searching around some more I find this solution (from Why doesn't my form post when I disable the submit button to prevent double clicking?)

if($.data(this, 'clicked')){
    return false;
} else{
    $.data(this, 'clicked', true);
    return true;
}

You can play with this using this fiddle: http://jsfiddle.net/uT3hP/1/

This does work, but...

Question 2: Is this the best we can do?

I thought this would be an elementary thing. Approach 1 does not work, approach 2 does, but I don't like it and sense there must be a simpler way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple and effective solution is

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

Source: here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...