I'm trying to display an alert box to show an error message on my web page. Initially, I had it working fine with the following code:
<div id="error" class="alert-er">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>Error!</strong>
</div>
<form>
<button type="submit" id="submit" class="submit">Submit</button>
</form>
And the associated CSS and JavaScript code:
.alert-er {
padding: 20px;
background-color: #ff2400;
color: #ffffff;
font-size: 20px;
border: 1px solid white;
border-radius: 20px;
}
.closebtn {
margin-left: 15px;
color: white;
font-weight: bolder;
float: right;
font-size: 40px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
However, when I made some changes to the JavaScript code to handle the display properties, the alert box started to appear and then disappear automatically in less than a second. Here's the updated JavaScript code:
document.getElementById("error").style.display = "none";
document.getElementById("submit").onclick = function() {
document.getElementById("error").style.display = "";
}
I've tried checking for errors and experimented with different approaches using CSS, JS, and jQuery, but the issue persists across all attempts.
I would greatly appreciate any assistance or guidance on how to fix this problem so that the alert box remains visible until I close it manually. Thank you in advance for your help!
The problem is that when you click the submit button, the form is being submitted.
To fix this, let's create an event listener for when the form is submitting. If we find an error, we don't let it continue the submission, and show the error message instead. We do this with the help of event.preventDefault():
const form = document.querySelector('form');
const errorMessage = document.getElementById("error");
form.addEventListener('submit', (event) => {
if(thereIsAnError()){
event.preventDefault();
errorMessage.style.display = "block";
}
})
function thereIsAnError(){
return true; // later, change this function to return true or false depending on your input values
}
document.getElementById("error").style.display = "none";