Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent form submission if validation failed after iterating over each form element with jquery's .each() function

I have the following code in which I'm trying to iterated over html text input elements, do some validation and prevent the form submission if the validation fails:

$("#the_form").submit(function(){
                $(":text", this).each(function(){                    
                    if($(this).val().length != 0)
                    {                            
                        var str = $(this).val();
                        str = $.trim($(this).val());
                        $(this).val(str);
                        if($(this).val().length < 4)
                        {
                            alert("You should enter at least 4 characters");
                            $(this).focus();
                            return false;
                        }
                    }                 
                }) // end of each() function
                return true;            
            })

If I remove the .each() function and do each element separately (which obviously is not a very good approach), I get the results wanted. However, if I use the code as it is, the form keeps on submitting even if the user has not entered at leas four characters. Any ideas on what I may be doing wrong here? Any help will be very appreciated. Thanks in advance.

like image 311
user765368 Avatar asked May 23 '11 03:05

user765368


People also ask

How do you stop form submit if the validation fails?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

How do I stop a form submission on enter?

You can also use javascript:void(0) to prevent form submission.

How do you prevent form submit on Enter in JavaScript?

This can be solved by writing the <input type='button'/> with javascript, and then put an <input type='submit' /> within a <noscript> tag. The drawback of this approach is that for javascript-disabled browsers you will then have form submissions on ENTER.

How do I stop a form from submitting in JQuery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.


2 Answers

Your return false; is from within the callback function for $.each() (which makes it break at that iteration) and not from the submit handler (which would stop the form submission). This should do the trick:

$("#the_form").submit(function(){
    var isValid = true;
    $(":text", this).each(function(){                    
        if($(this).val().length != 0)
        {                            
            var str = $(this).val();
            str = $.trim($(this).val());
            $(this).val(str);
            if($(this).val().length < 4)
            {
                alert("You should enter at least 4 characters");
                $(this).focus();
                isValid = false;
                return false;
            }
        }                 
    }) // end of each() function
    return isValid;
})
like image 55
no.good.at.coding Avatar answered Oct 19 '22 23:10

no.good.at.coding


Simple... You just prevent the default of the event if you want it to stop. Please DO NOT RETURN FALSE. Returning false from an event is like saying: "I want you to fail. Not only that I want to make sure that any event handler registered after me does not get executed, and no bubbling happens because some shit just went wrong". You want "prevent the action the browser does normally from happening".

$("#the_form").submit(function(e) {
  // LOGIC
  $(this).find(":text").each(function() {
      // OH NOES! We detected the form cannot be submitted.
      e.preventDefault();
      // More logic? maybe a shortcut exit.?
  });
});

note e.preventDefault() will stop links from going to their href target, will prevent form submission, will even prevent a change handler from allowing the change (say e.preventDefault() on a checkbox.change event). See http://api.jquery.com/event.preventDefault/

edit: Note that the event handler is always passed the event object as a parameter, in your code you just ignored it. Read up on event handler function. There are really nifty features that you can do with events in jquery, don't ingore them as they are quite useful at times especially when you need to get some data to the handler.

like image 26
Dmitriy Likhten Avatar answered Oct 20 '22 01:10

Dmitriy Likhten