0

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();
                    }
                });
            });
        });
beginneR
  • 3,207
  • 5
  • 30
  • 52

1 Answers1

1

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/

Community
  • 1
  • 1
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • thanks, but when i use `return = false;` instead, it immediately loads the next page. – beginneR Apr 01 '14 at 21:10
  • how do I check if the formular is valid or not? – beginneR Apr 02 '14 at 08:13
  • There are many ways to do that. My fav and the most reliable is to send all the data via Ajax to the server, let the server validate the data and return JSON with either success true or success false + error message. – Daniel W. Apr 02 '14 at 08:17
  • ok, but if I only want to use jquery. How do I have to change the function above to achieve this? – beginneR Apr 02 '14 at 08:54
  • You set a variable `isValid = true;` and when one field does not fit the requirements, you set `isValid = false` at the end you simply return this variable to abort or continue to submit. But keep in mind: client side validation is not reliable. Anyone can bypass Javascript and send wrong stuff to your server. – Daniel W. Apr 02 '14 at 09:01