使用 JavaScript 进行 HTML 表单操作和 onsubmit 验证?

javascriptweb developmentobject oriented programming更新于 2025/11/14 4:28:17

让我们看一个例子,其中我们在 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 −

单击搜索按钮后,您将收到一条警告消息,如下所示 −


相关文章


有用资源