4

I am trying to validate my form on submit and if the input's are all filled in they submit to register.php

My problem being it only works if all inputs are blank - otherwise it errors - I'm just trying to check if any of those fields are blank before submiting

function submitform() {
    if ($('#name, #email, #user, #address, #phone').val().length === 0) {
        $(this).addClass('warning');
    } else {
        alert("form submitted");
    }
}
4
  • Can you try == instead of === at line 2 ? Commented Aug 10, 2012 at 21:22
  • Doesn't submit if all fields are blank - submits if 1 field has text and the others are blank or if they all have text and vice versa Commented Aug 10, 2012 at 21:24
  • Have you looked at the documentation for the jquery api you are using? Commented Aug 10, 2012 at 21:25
  • @Andrew , i don't know jQuery very well, maybe there is a better way, but try this one : if(($('#name').val() > 0) && ($('#user').val() > 0) ....) alert('submitted') else alert('blank!') BETTER WAY = Jorge's answer Commented Aug 10, 2012 at 21:28

3 Answers 3

3

You cant do a .val on an array. It should be

function submitform(){
   var warning = false;
   $('#name, #email, #user, #address, #phone').each(function() {
      $(this).val().length === 0){
         warning = true;
         return;
      }
   });
   if(warning) {
      $(this).addClass('warning');
   } else {
      alert("form submitted");
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

you need to check each one of them with the each function in jquery, or a for loop.

$('#name, #email, #user, #address, #phone').each(function(){
    if ($(this).val().length === 0){
        $(this).addClass('warning');
    } else {
     alert("form submitted");
   }
});

Here's the same example with a for

var formElements = $('#name, #foo');

for (i = 0 ; i < formElements.length ; i++)
{
    if ( $(formElements[i]).val().length === 0 )
       $(this).addClass('warning');
    else {
       alert("form submitted");
    }
}

Comments

1
function formSubmit() {
    var pass = true;
    jQuery.each( jQuery('#form :input'), function( key, value ) {
       if(!this.value && jQuery(this).attr('class :contains("required")')) {
         if (jQuery(this).siblings('.error').length === 0 && jQuery(this).type != 'submit') {
            jQuery(this).after('<label class="error"><span class="form-required">*</span> Required</label>');
         }
         pass = false;
       } else {
        jQuery(this).siblings('.error').remove();
      }
    });
    if (pass === true) {
        document.getElementById('form').submit();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.