以HTML5格式在JavaScript中显示错误 [英] Show errors in JavaScript in HTML5 form

查看:296
本文介绍了以HTML5格式在JavaScript中显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含必填字段的HTML5表单:

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>

另外,我有以下jQuery代码:

Also, I have the following jQuery code:

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

我想在中强制显示HTML5错误//显示错误 line。

推荐答案

如果要显示验证气泡,首先应提交表格。将按钮的类型更改为提交并收听提交事件。

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.

另请注意,jQuery没有 checkValidity 方法,您应该首先获取原始DOM元素:

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/

这篇关于以HTML5格式在JavaScript中显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆