I'm facing an issue with my form where I want to prevent it from being submitted if the fields are blank and also highlight those blank fields. The code I currently have works when trying to submit with blank fields, but for some reason, it doesn't submit when the fields are filled out. I can't seem to figure out what's wrong. Any help would be greatly appreciated.
Here is the JavaScript code I am using:
function CheckFields(){
if((document.getElementById('title').value=="") || (document.getElementById("textfield").value=="")){
const formElement = document.querySelector('form');
formElement.addEventListener('submit',event =>{
event.preventDefault();
alert("Please fill out all fields before submitting");
document.getElementById("title").style.backgroundColor=red;
document.getElementById("title").style.backgroundColor=red;
});
}
And here is the relevant HTML code:
<input name="post" type="submit" value="Post" onclick="CheckFields();">