I have a form with multiple fields and the submit button is supposed to stay disabled until all of the :required fields are filled in. My problem is that the button becomes active when I start typing in the first field.
I’ve tried different things, from different questions on here, and I cannot get it to work.
Fiddle is below, and here is the code:
<form>
<div class="row">
<label for="realname">Name<span class="required">*</span></label>
<input type="text" name="realname" id="realname" required/>
</div>
<div class="row">
<label for="company">Company</label>
<input type="text" name="company" id="company"/>
</div>
<div class="row">
<label for="email">Email<span class="required">*</span></label>
<input type="email" name="email" id="email" required/>
</div>
<div class="row">
<label for="phone">Phone<span class="required">*</span></label>
<input type="tel" name="phone" id="phone" required/>
</div>
<div class="row">
<input type="submit" value="SUBMIT">
</div>
</form>
$(document).ready(function(){
var allInput = $('input:required');
var submit = $('input[type="submit"]');
submit.prop('disabled', true);
$('form').bind('submit',function(e){e.preventDefault();});
$(allInput).on('input change', function() {
$.each(allInput,function(){
if($(this).val() == ""){
console.log('nope');
} else {
submit.prop('disabled', false);
$('form').unbind('submit');
}
});
});
});
https://jsfiddle.net/cdpritch/vqcemxh6/
Thanks!
3
Answers
Your if block is not right. The if block is saying if one of those required fields is not blank, then enable the button. You want to check that all of them are not blank.
When one value is not an empty string you are enabling the button, I would do it the opposite way, enable the submit button and if one item is empty disable the button:
The code has been changed to get closer to optimal use of Jquery style code and to cover different use cases such as deleting already entered values.