Search code examples
javascriptjqueryvalidationpreventdefault

event.preventDefault not working when validating radio buttons


I am trying to validate if all items (radio buttons) are checked. The following code works, but as soon as I click on the alert-window, it pops up again. Using event.stopPropagation() doesn't change anything. It is not waiting for the user to check the remaining items.

$(document).ready(function(){
        $(document).on('submit','#formular',function(event){
            $("input:radio").each(function() {
                var val = $('input:radio[name=' + this.name + ']:checked').val();
                if (val === undefined) {
                    alert("Not every item answered");
                    event.preventDefault();
                    }
                });
            });
        });

Solution

  • You don't quit a loop using preventDefault, normally you would use break or continue, but on a jQuery $.each you must use return true to continue and return false equivalent to break.

        $(document).ready(function(){
            $(document).on('submit','#formular',function(event){
                $("input:radio").each(function() {
                    var val = $('input:radio[name=' + this.name + ']:checked').val();
                    if (val === undefined) {
                        alert("Not every item answered");
                        return false;
                    }
                });
                // When invalid formular:
                return false;
                // When it's valid:
                return true;
            });
        });
    

    See also this question: jquery validation: prevent form submit

    See:

    How to break out of jQuery each Loop

    How to break/exit from a each() function in JQuery?

    https://api.jquery.com/each/