【问题标题】:Trigger invalid event jquery触发无效事件jquery
【发布时间】:2016-11-07 14:43:33
【问题描述】:

自定义函数可以在不提交表单的情况下触发“无效弹出”吗?

弹出窗口无效 -> https://www.html5rocks.com/static/images/tutorials/constraintvalidation/ChromeForAndroid.png

【问题讨论】:

  • 那是 HTML5 验证,与 jQuery 无关。但你可以使用.on('keyup') 事件。
  • 不行,不能触发弹窗,只能触发验证
  • 您可以对 'keyup'、'keydown'、'input' 事件执行验证

标签: jquery html forms input


【解决方案1】:

假设你有一个input

<input type="text" id="input_id">

使用 jquery,您可以执行此验证:

$(document).on("keyup", "#input_id", function(){
    if( $(this).val() == '' )
    {
        /* show error message here */
    }
});

或者如果你想使用纯 JavaScript,你可以使用:

var el = document.getElementById('input_id'); 

el.addEventListener("keyup", function() {
    validate_me(this);
}, false);

function validate_me(e)
{
     if(e.value == '')
     {
          /* error message here */
     }
}

如果您只需要 html5 解决方案:

要检查某个字段是否有效,请使用:

$('#myField')[0].checkValidity() // returns true/false

要检查表单是否有效,请使用:

$('#myForm')[0].checkValidity() // returns true/false

如果您想显示某些浏览器(例如 Chrome)的原生错误消息,不幸的是,唯一的方法是提交表单,如下所示:

var $myForm = $('#myForm')
if (!$myForm[0].checkValidity()) {
    // If the form is invalid, submit it. The form won't actually submit;
   // this will just cause the browser to display the native HTML5 error messages.
  $myForm.find(':submit').click()
}

请记住,并非所有浏览器都支持 HTML5 验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多