It is possible to solve the problem in a more "generic" way, that is, by creating a kind of camp group using CSS classes.
A possible HTML would look like this:
<select class="meu_grupo" id="cbExercicio"><option value="0"></option><option value="1">1</option></select>
<select class="meu_grupo" id="cbEquipe"><option value="0"></option><option value="1">1</option></select>
<select class="meu_grupo" id="cbResponsavel"><option value="0"></option><option value="1">1</option></select>
So the code goes like this:
$(function() {
$('.meu_grupo').change(function() {
//itera sobre os elementos
var falta_preencher = false;
$('.meu_grupo').each(function() {
if (!this.selectedIndex) falta_preencher = true;
});
//verifica o resultado
if (falta_preencher) alert('Preencha todos...')
else alert('Preencheu todos!');
})
});
See the jsfiddle working.
The idea is to place a change event in all fields that have the class meu_grupo
and, when an event occurs, check that all fields in the same group are duly filled in.
Obviously, the type of validation and the action resulting from all fields being correct is at the discretion of the implementation.
Note that I linked the event change
directly to the fields with the class meu_grupo
, as this is more efficient than capturing all document events and filtering only the desired fields. Unless you have other reasons to use it on
in the document, give preference to specific events. Follow the same example using the on
:
$(function() {
$(document).on('change', '.meu_grupo', function() {
//itera sobre os elementos
var falta_preencher = false;
$('.meu_grupo').each(function() {
if (!this.selectedIndex) falta_preencher = true;
});
//verifica o resultado
if (falta_preencher) alert('Preencha todos...')
else alert('Preencheu todos!');
})
});
Note also that the validation of my example will make an implicit conversion from the text "0" to false
. The effect would be the same if the value of the first element were empty.
When do you need to check this?
– bfavaretto
I updated my bfavaretto
– Joao Paulo