jQuery make sure all form fields are filled

前端 未结 4 1189
北恋
北恋 2020-12-05 15:41

I have a simple form I\'m making client side validation for. To validate, none of the fields should be left blank. This is how I go at it:

function validateF         


        
4条回答
  •  日久生厌
    2020-12-05 16:33

    You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:

    function validateForm() {
      var isValid = true;
      $('.form-field').each(function() {
        if ( $(this).val() === '' )
            isValid = false;
      });
      return isValid;
    }
    

    Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')

    EDIT Ah, I got beat to the punch, but my explanation is still valid and hopefully helpful.

提交回复
热议问题