當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。