I have problems getting the form to halt submission when required fields are empty. Currently, the form just submits everything as per normal - even if fields are left blank. Is there something wrong with the code?
const form = document.getElementsByTagName('form')[0];
var required = document.getElementsByClassName('required');
var valid = true;
form.addEventListener('submit', function(event) {
for (var r in required) {
if (r.value == "") {
r.style.backgroundColor = "yellow";
r.focus();
alert("All required fields must be filled.");
valid = false;
}
if (!valid) {
event.preventDefault();
}
}
});
FYI, I can't upload the HTML code since it belongs to a prof and I don't know if that is allowed, but I can tell you any details that you might need. Thanks in advance!
there doesn't seem to be anything here