当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML oninvalid事件用法及代码示例


当我们提交无效的元素时,将发生HTML DOM oninvalid事件。例如,输入字段是可提交的,并且设置了必填属性,则如果该字段为空,则该属性无效。

用法:

  • 在HTML中:
    <element oninvalid="myScript">
  • 在JavaScript中:
    object.oninvalid = function(){myScript};
  • 在JavaScript中,使用addEventListener()方法:
    object.addEventListener("invalid", myScript);

范例1:使用HTML。


<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
      HTML DOM oninvalid Event 
  </title> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2> 
          HTML DOM oninvalid Event 
      </h2> 
        <form> 
            email:
            <input type="email"
                   oninvalid=""
                   name="email" 
                   required> 
            <br> 
            <input type="submit"
                   value="Submit"> 
        </form> 
    </center> 
</body> 
  
</html>

输出:

范例2:使用JavaScript。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML DOM oninvalid Event 
    </title> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2> 
          HTML DOM oninvalid Event 
      </h2> 
        <form> 
            Email:
            <input type="email" 
                   id="emailid"
                   name="email" 
                   required> 
            <br> 
            <input type="submit" 
                   value="Submit"> 
        </form> 
  
        <script> 
            document.getElementById( 
              "emailid").oninvalid = function() { 
                (GFGfun) 
            }; 
  
            function GFGfun() { 
                alert("Please fill out the required fields."); 
            } 
        </script> 
    </center> 
</body> 
  
</html>

输出:

范例3:使用addEventListener()方法:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML DOM oninvalid Event 
    </title> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2> 
          HTML DOM oninvalid Event 
      </h2> 
  
        <form> 
            Email:
            <input type="email" 
                   id="emailid"
                   name="email"
                   required> 
            <br> 
            <input type="submit"
                   value="Submit"> 
        </form> 
  
        <script> 
            document.getElementById( 
                "emailid").addEventListener( 
                "invalid", GFGfun); 
  
            function GFGfun() { 
                alert( 
                    "Please fill out the required fields."); 
            } 
        </script> 
    </center> 
</body> 
  
</html>

输出:
之前:

后:

支持的浏览器:下面列出了HTML DOM oninvalid Event支持的浏览器:

  • 谷歌浏览器
  • Internet Explorer 10.0
  • Firefox
  • 苹果Safari
  • Opera


相关用法


注:本文由纯净天空筛选整理自Vijay Sirra大神的英文原创作品 HTML | DOM oninvalid Event。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。