I’m trying to get values from HTML but every time I click the submit button there is a glitch. The output is showing as expected but only for a millisecond. I’m new to coding, kindly guide me.
HTML:
var my_name = "harhu";
var my_password = "harshali";
function my_form() {
var a = document.getElementById("nameForm").value;
var b = document.getElementById("passForm").value;
if (a == my_name && b == my_password) {
document.body.style.backgroundColor = "green";
document.getElementById("result").innerHTML = "Access granted! Welcome!";
} else {
document.body.style.backgroundColor = "red";
document.getElementById("result").innerHTML = "Access denied! Try again.";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Values from HTML</title>
</head>
<body>
<h1>To receive values from HTML</h1>
<form>
<p>Name</p>
<input type="text" id="nameForm" value="">
<p>Password</p>
<input type="text" id="passForm">
<button onclick="my_form()">Submit</button>
<p id="result">-------</p>
</form>
<script src="valuesFromHtml.js"></script>
</body>
</html>
The code is working, but the output is shown only for a mere second, it’s a glitch of sorts? The code is working seamlessly when I use the event.preventDefault()
but it should work without it too, right?
2
Answers
I thing you should change your button tag to input with type button
Before:
After:
I hope it helps you
This is not a glitch
button
tab will submit the form by default. That’s the reason you see the color temporarily.You can change the component from
<button>
to<input type="button">
as mentioned in the other answer.Or
In your button tag
onclick
event, addreturn false;
at the end. this will be helpful when CSS is based on the element type.