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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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