[英]How to call a function on form submit using external js file
I want to call a function when the user submit a form, and how to achieve this with external JS
script.我想在用户提交表单时调用一个函数,以及如何使用外部JS
脚本来实现这一点。
index.html索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>teste</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link type="text/javascript" src="main.js">
</head>
<body>
<h1 class="title">teste</h1>
<form action="a()">
<input type="input1" class="input1" name="verb" id="verb" placeholder="Verb"/>
</form>
</body>
</html>
main.js主文件
function a(){
alert("verb");
}
You could add event listener
on onsubmit
event of form and you can add the external scripts by using script
tag.您可以在表单的onsubmit
事件上添加event listener
,并且可以使用script
标记添加外部脚本。
Example: how to add external JS file.示例:如何添加外部 JS 文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>teste</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="./main.js"></script>
</head>
<body>
//.. html
</body>
</html>
Working Example:工作示例:
let formElem = document.getElementById("form"); formElem.addEventListener("submit", formSubmitHandler); function formSubmitHandler(event) { event.preventDefault(); console.log("Form submitted"); console.log("User entered: " + event.target.elements[0].value); }
<h1 class="title">teste</h1> <form id="form"> <input type="input1" class="input1" name="verb" id="verb" placeholder="Verb" /> <button type="submit" >Submit</button> </form>
You can add the formSubmitHandler
in the main.js
file.您可以添加formSubmitHandler
在main.js
文件。
Follow This code...按照这个代码...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>teste</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1 class="title">teste</h1>
<form >
<input type="text" name="text" id="input" placeholder="Verb" />
<input type="submit" onclick="a()">
</form>
<script src="./index.js"></script>
</body>
</html>
function a() {
alert('hello');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.