html code
<div id="signup">
<form id="suform" method="POST" action="roma/roma">
<p>
<label>Frist Name</label>
<input type="text" id="sufName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Last Name</label>
<input type="text" id="sulName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" id="suEmail"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Mobile Number</label>
<input type="text" id="suMNumber"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" id="suPassword"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Re Password</label>
<input type="password" id="suRePassword"/>
<span class="errorMessage"></span>
</p>
<p>
<input type="submit" class="button" value="sign up"/>
</p>
</form>
</div>
it is just six input fields to make a sign up page
and this is the jQuery code to ensure that there is no input field empty, and if there is no input field empty I want to submit the form.
jQuery code
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
$(this).submit(); // submit form if no error
}
});
});
The code ensure that there is no input field empty, it found an empty one then an error message will appear, else should submit, but the submit doesn’t work.
Try using
$(this)[0].submit();. Using $(this) refers to the jQuery object reference to the form. I don’t know what jQuery’ssubmit()method actually does, but it clearly doesn’t submit the form. Using$(this)[0]refers to the actual DOM element, which will use the standard DOM submit method, which is what you’re looking for.I’m sure you know this already, but you should use server and client side validation, because some users don’t have JS and some users will purposely tamper with your form. Just a quick “Don’t forget”!