JavaScript 中 HTML 表單動作和 onsubmit 驗證?
讓我們看一個例子,我們在其中 onsubmit 驗證輸入文字 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form onsubmit="return validateTheForm()" method="GET" action="https://mail.google.com/mail/">
<br/>
<input type="text" id="txtInput" value=""/>
<input type="submit" value="search"/>
</form>
<script>
function validateTheForm(){
var validation = (document.getElementById('txtInput').value == 'gmail');
if(!validation){
alert('Something went wrong...Plese write gmail intext box and click');
return false;
}
return true;
}
</script>
</body>
</html>要執行上述程式,請儲存檔名“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
這將產生以下輸出 −

步驟 1
在文字框中輸入 GMAIL −

在單擊搜尋按鈕後,輸出如下 −

步驟 2
在輸入除 GMAIL 以外的另一個值時,將收到一條提醒訊息。
我們先輸入值,然後按 Enter −

在單擊搜尋按鈕後,您將收到以下輸出中的提醒訊息 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP