0

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>&nbsp;&nbsp;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?

1
  • It'd be awesome if you could include a JSFiddle demonstrating the issue Commented Aug 13, 2014 at 18:12

1 Answer 1

1

Set hasError = false before the loop starts. Then only set hasError = true if an error occurs.

The last good one will never overwrite the false value.

hasError = false;
$.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>&nbsp;&nbsp;Please complete all proficiencies.</div>');
            hasError = true;
        }else{
            $('[name="'+name+'"]').closest('tr').removeClass('danger');
        }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you - I had it false already by default, just had to remove the hasError=false line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.