Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - How to bind to the submit event when HTML5 validation is used?

Using HTML5 validation...

In HTML5 browsers, validation occurs before the submit event. So if the form is invalid, the submit event never fires.

I would like to hook an event into the form submit, to fire whether the form validates or not. Here's a small example, where I'm trying to alert() when the user submits the form.

HTML:

<!DOCTYPE html>
<html>
    <head><title>Example</title></head>
    <body>
        <form>
            <input type="text" name="foo" required title="Foo field"/>
            <input type="submit"/>
        </form>
    </body>
</html>

JavaScript:

$(function() {
    $('form').submit(function() {
        alert('submit!')
    });
});

Interactive demo: http://jsfiddle.net/gCBbR/

My question is: do browsers provide an alternative event that I can bind to that will run before the validation?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, there is an event for that reason. The event is called invalid when user tries to submit the for orr when you check validity via HTML5 validation method checkValidity(). This event does not fire on blur or something like that without calling checkValidity() just because you have HTML validation attributes in your input tags. But it does fire on before form submit.

From W3C:

When the checkValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must fire a simple event named invalid that is cancelable (but in this case has no default action) at the element and return false. Otherwise, it must only return true without doing anything else.

For example you have this markup:

<form>
            <input type="text" name="foo" required title="Foo field"/>
            <input type="submit"/>
</form>

Then you need to call checkValidity() to fire invalid event if the input data is invalid:

document.querySelectorAll('input')[0].addEventListener('blur', function(){
        this.checkValidity();
    }, false);

document.querySelectorAll('input')[0].addEventListener('invalid', function(){
        console.log('invalid fired');
    }, false);

Look at my example here: http://jsbin.com/eluwir/2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...