I need to do a check on a page that will show a message when the first 3 form fields on a page are all empty. I can write the checks and show the message, but I am not certain what the correct way to handle the "while" part is in js/jquery. I could just put this in a loop that runs every 100ms but I am 100% sure that its absolutely wrong.
var empty = true;
$('input[type="text"].slice(0,3)').each(function() {
if ($(this).val() != "") {
empty = false;
return false;
}
});
if (empty) {
document.getElementById('interactive-warning').style.display = 'none';
};
What is the "correct" way to do this?
The working code:
$(document).ready(function(){
$('.form-text').slice(0,3).on('input', function() {
var empty = true;
$('.form-text').slice(0,3).each(function() {
if ($(this).val() != "") {
empty = false;
return false;
}
});
if (!empty) {
document.getElementById('interactive-warning').style.display = 'none';
} else {
document.getElementById('interactive-warning').style.display = 'block';
};
}).trigger('input');
});
I needed to execute on ready because the code needed to be added before the form.
You can listen to the input event, which will let you know when the user changes those values, eg:
move your existing code into function checkIfEmpty() { ... and add:
$('input[type="text"].slice(0,3)').on("input", checkIfEmpty);
(note there's no () after checkIfEmpty on the event)
If your inputs are changed via code, the UI events aren't raised, so you'll need an alternative. The easiest way is: when your code changes the inputs, also call checkIfEmpty().