Question: This is an HTML and Javascript question. In HTML, I have a form with some fields and a submit button. HTML links to a .js
This is an HTML and Javascript question.
In HTML, I have a form with some fields and a submit button. HTML links to a .js file which should handle form checking when the user hits submit. If the user leaves a required field blank, the error CSS class should toggle on, on the field that is blank. I have tried doing this two different ways, in document.getElementById("mainForm").addEventListener("submit", function(e) (commented out), and document.getElementById('mainForm').addEventListener("submit", validate), but neither work. What am I doing wrong?
HTML:
Javascript:
/*function checkField(e) {
if (e.target)
}*/
/*document.getElementById("mainForm").addEventListener("submit", function(e) {
var cssSelector = ".required";
var fields = document.querySelectorAll(cssSelector);
for (i=0; i if (fields[i].value == null || fields[i].value == "") { fields[i].classList.add('error'); e.preventDefault(); } } });*/ document.getElementById('mainForm').addEventListener("submit", validate); function validate() { var title = document.getElementById('title').value; var description = document.getElementById('description').value; var year = document.getElementById('year').value; if (title == null || title == "") { document.getElementById('title').classList.add('error'); event.preventDefault(); } if (description == null || description == "" ) { document.getElementById('description').classList.add('error'); event.preventDefault(); } if (year == null || year == "") { document.getElementById('year').classList.add('error'); event.preventDefault(); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
