Event Listener valid for HTML5 forms

前端 未结 4 1526
半阙折子戏
半阙折子戏 2020-12-18 19:41
  1. New on HTML5 there\'s an \"invalid\" event, to which you can add a listener:

    document.addEventListener(\'invalid\', function(e){
       var element = $(         
    
    
            
4条回答
  •  太阳男子
    2020-12-18 20:01

    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/

提交回复
热议问题