I'm trying to check if all input fields with a certain class are empty. Right now I have the following code:
HTML
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<button class="check-fields">Check Fields</button>
jQuery
$('.check-fields').on('click', function () {
var value = $('.required-entry').filter(function () {
return this.value != '';
});
if (value.length == 0) {
alert('Please fill out all required fields.');
} else if (value.length > 0) {
alert('Everything has a value.');
}
});
But this throws the message "Everything has a value." if ANY one of the inputs has a value. I'm trying to only throw that message when every input with this class has something in it.
$('.check-fields').on('click', function () {
var value = $('.required-entry').filter(function () {
return this.value != '';
});
if (value.length == 0) {
console.log('Please fill out all required fields.');
} else if (value.length > 0) {
console.log('Everything has a value.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<button class="check-fields">Check Fields</button>
I also have this fiddle with slightly different code.. also throws the Everything has a value message when the first input is the only one filled.
$('.check-fields').on('click', function () {
if($.trim($('.required-entry').val()) === '') {
console.log('Please fill out all required fields.');
} else {
console.log('Everything has a value.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<button class="check-fields">Check Fields</button>
this.value === '';
This way you know that at least 1 has nothing in it.return this.value != '';
? This makes it always say please fill out all required fields