简体   繁体   中英

action button after the second click

I have a button in my form. I need my form to be processed after the first click (or pressing Enter) on the button, and after that, if some conditions would be true, I do something like submitting the form by the second click or pressing Enter key on the button.

What do you think I have to do?

Create a (boolean) variable that saves your state, which is set to true when the first click (or action) has happened and your condition is true. Then submit on the second action when the variable is true.

If the condition has to be matched on both clicks (I guess so) consider the following:

$(function() {
    var first = false;
    $("form").submit(function() {
        if(first && checkCondition())
            submit();
        if(!first && checkCondition())
            first = true;
        e.preventDefault();
    });
});

so in basic code:

var answered = false;
$(function() {
    $("form").submit(function() {
        if(answered == false) {
            answered = true;
            return false;
        }
    });
});

If I've understood what you're trying to do correctly, you could bind an event handler to the submit event. That event handler will handle your validation, but if you use the jQuery one method, it will only be executed once. The next time the submit event is triggered, the form will submit as usual:

$("yourForm").one("submit", function(e) {
    e.preventDefault(); //Stop the form from being submitted
    //Do stuff
});

The result is effectively the same as @Manuel van Rijn's answer, but using jQuery's one just makes it a bit shorter and cleaner in my opinion. However, this could also add a slight performance benefit, as the event handler is unbound after it's execution and won't be called again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM