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

javascript - Event Listener valid for HTML5 forms

  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?


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

Thanks in advance,

óscar

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

$(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/.

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.)

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

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


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

...