views:

51

answers:

2

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?

A: 

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) {
     ...
karim79
This will fail if any hidden or other non-required input has a blank value.
Mike Samuel
@mikesamuel - I fail to see how. Was a down-vote really necessary?
karim79
A: 

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>
Mike Samuel
onsubmit="checkMyForm(this)" = intrusive javascript = yuck.
karim79
that looks great but I don't understand that if(/\breq\b/.test(... line, can you tell me what is going on there?
shogun