I have a jQuery loop that is looking over radio buttons on the page and makes sure that they are checked.
The function is working but there is a glitch and I know why; just not sure how to fix it.
// Validate the proficiencies
var names = {};
$('.radio').filter(':radio').each(function(){
var name = $(this).attr('name');
if( undefined === names[name] ){
names[name] = false;
}
if( $(this).is(':checked') ){
names[name] = true;
}
});
$.each(names, function(name, val){
if( !val ){
theTab = 'proficienciesTab';
$('.nav-tabs a[href="#' + theTab + '"]').tab('show');
$('[name="'+name+'"]').closest('tr').addClass('danger');
$('[name=error]').empty().append('<div class="alert alert-danger" role="alert"><i class="fa fa-ban"></i> Please complete all proficiencies.</div>');
hasError = true;
}else{
$('[name="'+name+'"]').closest('tr').removeClass('danger');
hasError = false;
}
});
if(!hasError){
//process form
}
The issue is in the $.each loop. If there are 10 radio buttons and all are left uncheck, it works fine as they all return false.
However, if I were to only check the last radio button, it will return false for all of them and then true on the last so the final hasError value will be true thus executing the next piece of code and processing the form.
If I just return false inside here if( !val ){ } it wont add the classes to the ones missing, it will only add it to the first one it finds false.
How can I fix this?