How to call a function on form submit using external js file
You could add
event listener
on onsubmit
event of form and you can add the external scripts with the help of script
tag.
Example: how to add external JS file.
<!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.
Aucun commentaire