In my HTML form, I would like to use a button for submitting a form instead of input type submit. I have got a javascript code to give an error if the email if empty, also to prevent the form from submitting. However, the code does not seem to work and I get this error: Cannot GET /submit The weird thing is that the code works here in stackoverflow when you run it!
const email = document.getElementById('email'); const form = document.getElementById('form'); const emailMessage = document.getElementById('email-message'); form.addEventListener('submit', e => { if (email.value === '' || email.value === null) { emailMessage.innerHTML = 'where is the email'; e.preventDefault(); } else { return true; } });
<form id="form" action="submit"> <input id="email" type="email" /> <button type="submit">Go</button> <p id="email-message"></p> </form>
Why not just use the required
attribute? No JS necessary
<input id="email" type="email" required>
This will check if the email field is not empty and additionally entered string is a valid email format.
Note that HTML "required" does not work in safari browser whose version less than Safari 10.1 (May 2017)
Edit: To display a custom message, subscribe to the invalid
event
const email = document.getElementById('email');
email.addEventListener('invalid', function(e){
if (email.value == '')
email.setCustomValidity('Where is the email?');
else if (email.validity.typeMismatch)
email.setCustomValidity('Email address be invalid!');
});
You can learn more about Form Validation at Mozilla
Your code works fine. try this
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="form" action="submit">
<input id="email" type="email"/>
<button type="submit">Go</button>
<p id="email-message"></p>
</form>
<script>
const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('email-message');
form.addEventListener('submit', e => {
if (email.value === '' || email.value === null) {
emailMessage.innerHTML = 'where is the email';
e.preventDefault();
} else {
return true;
}
});
</script>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.