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
834 views
in Technique[技术] by (71.8m points)

jquery - Show errors in JavaScript in HTML5 form

I have a HTML5 form with required fields:

<form id="my_form">
    <input type="text" name="myfield1" required>
    <input type="text" name="myfield2" required>
    <input type="text" name="myfield3" required>
    <button type="button" id="my_button">Check</button>
</form>

Also, I have the following jQuery code:

$('#my_button').on('click', function() {
    if ($('#my_form').checkValidity() == false) {
       //show errors
    }
});

I would like to force show HTML5 errors in //show errors line.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you want to show the validation bubbles, at first the form should be submitted. Change the type of the button to submit and listen to submit event.

Also note that jQuery doesn't have checkValidity method, you should at first get the raw DOM element:

// on submit event browser will validate the form and show the bubbles
$('#my_form').on('submit', function() {
    if (this.checkValidity() == false) {
        return false;
    }

   // ...

});

http://jsfiddle.net/m5duh44x/


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

...