Javascript 事件监听器对 HTML5 表单有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7946714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:10:03  来源:igfitidea点击:

Event Listener valid for HTML5 forms

javascriptformshtmlvalidationaddeventlistener

提问by óscar

  1. New on HTML5 there's an "invalid" event, to which you can add a listener:

    document.addEventListener('invalid', function(e){
       var element = $(e.target);
       element.addClass("invalid");
       element.parent().addClass("invalid");
    }, true);
    

    Please note, this event just works when submitting the form... If I style the input input:invalid { background: red }, the style is applied when the user starts typing and his input is not valid. Is that event only fired on submit? I tried adding the listener to the inputs themselves instead of the document and it didn't work.

  2. I add a listener in order to apply a style to the input's parent... Now, when the user corrects it, it's valid again... I know there's not a "valid" event, so, how can I accomplish it?

  1. HTML5 新增了一个“无效”事件,您可以向其中添加一个侦听器:

    document.addEventListener('invalid', function(e){
       var element = $(e.target);
       element.addClass("invalid");
       element.parent().addClass("invalid");
    }, true);
    

    请注意,此事件仅在提交表单时起作用...如果我为 inputinput:invalid { background: red }设置样式,则在用户开始输入且他的输入无效时应用该样式。该事件仅在提交时触发吗?我尝试将侦听器添加到输入本身而不是文档中,但它不起作用。

  2. 我添加了一个侦听器以便将样式应用于输入的父级......现在,当用户更正它时,它再次有效......我知道没有“有效”事件,那么,我该如何完成它?



Ok, so here's a fiddle --> http://jsfiddle.net/Osoascam/ceArQ/7/The invalid listener seems to be only fired on submit... I just wanted to know whether there's a way to add a handler just like there is for focus. See that if you type a

好的,这里有一个小提琴 --> http://jsfiddle.net/Osoascam/ceArQ/7/无效的监听器似乎只在提交时被触发......我只是想知道是否有一种方法可以添加一个处理程序就像有焦点。如果你输入一个

Thanks in advance,

提前致谢,

óscar

奥斯卡

采纳答案by alexander farkas

You should use the :invalid pseudo selector and the input or the change event, to solve your problem.

您应该使用 :invalid 伪选择器和输入或更改事件来解决您的问题。

$(document).bind('change', function(e){
    if( $(e.target).is(':invalid') ){
        $(e.target).parent().addClass('invalid');
    } else {
        $(e.target).parent().removeClass('invalid');
    }
});

Here is a simple fiddle http://jsfiddle.net/trixta/YndYx/.

这是一个简单的小提琴http://jsfiddle.net/trixta/YndYx/

If you want to remove the error class as soon as possible you should add the error class on change and remove it on the input event (Note: input event is much better than here suggested keyup, simply because it also is triggered on paste etc., but it only works with input elements, not textarea.)

如果你想尽快删除错误类,你应该在更改时添加错误类并在输入事件中删除它(注意:输入事件比这里建议的 keyup 好得多,因为它也是在粘贴等时触发的。 ,但它仅适用于输入元素,不适用于 textarea。)

And here is a fiddle using a mixture of input and change event: http://jsfiddle.net/trixta/jkQEX/

这是一个混合使用输入和更改事件的小提琴:http: //jsfiddle.net/trixta/jkQEX/

And if you want to have this cross browser you can simply use webshims libto polyfill. Here is a x-browser example: http://jsfiddle.net/trixta/RN8PA/

如果你想拥有这个跨浏览器,你可以简单地使用webshims lib填充。这是一个 x 浏览器示例:http: //jsfiddle.net/trixta/RN8PA/

回答by Rob W

Since these classes are always added when a form is submit, remove the class prior validating:

由于这些类总是在提交表单时添加,因此在验证之前删除该类:

$('#myForm').submit(function(){
    $('.invalid', this).removeClass('invalid'); // Remove all invalid classes
    $(this).removeClass('invalid');             // If the parent = form.
    // Normal validation procedure.
});

Expected result:

预期结果:

  1. User initiates submit
  2. onsubmitis triggered > All invalidclass names within the form are removed.
  3. The invalidevents are triggered, and the invalidclasses are added when necessary
  1. 用户发起 submit
  2. onsubmit被触发 >invalid删除表单中的所有类名。
  3. invalid事件被触发,invalid类添加必要的时候

Update

更新

Added an extra block to your fiddle, see updated fiddle: http://jsfiddle.net/ceArQ/10/. I have implemented the checkValidity()method and the validity.validproperty. Now, the classes are automatically added when the input is invalid.

向您的小提琴添加了一个额外的块,请参阅更新的小提琴:http: //jsfiddle.net/ceArQ/10/。我已经实现了checkValidity()方法和validity.valid属性。现在,当输入无效时会自动添加类。

document.addEventListener('keyup', function(e){
    var input = e.target;
    if (!$.nodeName(input, 'input')) return;
    input.checkValidity();
    var element = $(input).parent();
    if(input.validity.valid) {
        element.removeClass('invalid');
        element.parent().removeClass('invalid');
    } else { //Remove the lines below if you don't want to automatically add
             // classes when they're invalid.
        element.addClass('invalid');
        element.parent().removeClass('invalid');
    }
});

On key-up, the validity of an input element is checked. If it's valid, the invalidclass is removed from its parent.

在启动时,检查输入元素的有效性。如果有效,则invalid该类将从其父类中删除。

回答by mAu

You could bind your validation logic to the focusand blurevents, or to be even more responsive, to the keyupevent.

您可以将验证逻辑绑定到focusblur事件,或者对事件做出更快的响应keyup

$('input').keyup(function() {
    if(isValid(this)) {
        $(this).removeClass('invalid').parent().removeClass('invalid');
        $(this).addClass('valid').parent().addClass('invalid');
    }
    else {
        $(this).removeClass('valid').parent().removeClass('valid');
        $(this).addClass('invalid').parent().addClass('invalid');
    }
});

回答by Raynos

Have you tried using :validto give an indicator as to whether a field is valid. and having forms that are invalid just keep their default styling.

您是否尝试过使用:valid来指示字段是否有效。并且具有无效的表单仅保留其默认样式。

Then calling form.checkValidity()in the submit handler? (The browser should then tell the end-user which form element is not valid).

然后调用form.checkValidity()提交处理程序?(然后浏览器应该告诉最终用户哪个表单元素无效)。