Jquery Verification Form

I try to validate my form with submit and if they are all filled out they submit to register.php

My problem is that it only works if all the inputs are empty - otherwise these are errors. I'm just trying to check if any of these fields are empty before submitting

function submitform() { if ($('#name, #email, #user, #address, #phone').val().length === 0) { $(this).addClass('warning'); } else { alert("form submitted"); } } 
+4
source share
3 answers

You cannot do .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"); } } 
+3
source

you need to check each of them using the each function in jquery or the for loop.

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

Here is 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"); } } 

+2
source
 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(); } } 
+1
source

All Articles