I want it so when they click on the submit button it will first check all the fields with class="req" and if any are empty it will cease to submit and give them an error, otherwise the submit should go through.
How can I do this?
I want it so when they click on the submit button it will first check all the fields with class="req" and if any are empty it will cease to submit and give them an error, otherwise the submit should go through.
How can I do this?
This should do it:
document.getElementById('myForm').onsubmit = function() {
var elems = document.getElementsByClassName('req');
for(var i = 0; i < elems.length; i++) {
if(elems[i].value.length == 0) {
return false;
}
}
}
That will attach the function to your form's submit event. If any of those elements are empty, the function will return false immediately, preventing the form from being submitted.
If you don't want whitespace-only values to be counted as filled, you can replace the if condition in the above with this:
if(elems[i].value.replace(/^\s+|\s+$/g,"").length == 0) {
...
Adding an "onsubmit" event handler to the form will let you take action when you need to.
<form onsubmit="checkMyForm(this)">
...
</form>
Then you can define a handler
<script>
function checkMyForm(myForm) {
for (var i = 0; i < myForm.elements.length; ++i) {
var input = myForm.elements[i];
if (/\breq\b/.test(input.className) && !input.value) {
// Has an empty required input
alert('Please enter all required inputs');
input.focus();
return false; // abort form submission
}
}
}
</script>