#1
Check your selectors. A selector like this #login #submit
might select the right element, but since IDs have to be unique in HTML to make it valid, it is redundant to have the #login
preceeding the #submit
.
#login input.required
should be #login input[required]
.
#2 In Addition to that you have an error in your condition.
$('#login input.required').each(function() {
empty = $(this).val().length == 0;
});
This basically only checks your last element. If the second to last element is empty, but your last element is not your variable empty
will be false
although you actually have empty fields.
To avoid that, you need to break out of the each loop as soon as you find an empty field, or only overwrite the variable if you find an empty field.
$('#login input.required').each(function() {
empty = $(this).val().length == 0;
return false;
});
#3 Always use trim()
to check if a value is truely empty!
$('input').on('keyup', isValid);
function isValid() {
let requiredInputs = $('input[required]');
let emptyField = false;
$.each(requiredInputs, function() {
if( $(this).val().trim().length == 0 ) {
emptyField = true;
return false;
}
});
if(!emptyField) {
$('button').attr('disabled', false);
}else{
$('button').attr('disabled', true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" required="required" />
<input type="text" />
<input type="text" required="required" />
<input type="text" required="required" />
<button disabled="disabled">
Submit
</button>