It is possible to solve the problem in a more generic way, that is, by creating a kind of group of fields 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>
Then the code looks 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 jsfiddle running .
The idea is to put a change event on all fields that have the class meu_grupo
and, when an event occurs, check that all fields in the same group are properly populated.
Obviously, the type of validation and the resulting action of all fields are correct is at the discretion of the implementation.
Note that I linked the change
event directly to fields with the meu_grupo
class, as this is more efficient than capturing all document events and filtering only the desired fields. Unless you have other reasons for using the on
handler in the document, give preference to specific events. Follow the same example using 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 do an implicit conversion of the text "0" to false
. The effect would be the same if the value of the first element was empty.