s3yfullah
s3yfullah

Reputation: 165

Jquery multi submit event

I coded, global mini form validation for jquery. This here; This code, All form submit event listener.

$('form').submit(function() {
       var returnfalse = 'true';
        var min;
        var maxlength;

        $('input[type=text], input[type=password]', this).removeClass('error');

        jQuery.each( $('input[type=text], input[type=password]', this) , function() {


            min = $(this).attr('min');
            maxlength = $(this).attr('maxlength');
            inputValue = $(this).val().trim();



            if( $(this).attr('min') != '' && $(this).attr('min') != null && inputValue.length < min ) {
                alert('ERROR !!!!!')
                $(this).addClass('error');
                $(this).focus();
                returnfalse = 'false';
            }



            if(returnfalse != 'true')
                return false;


        });

        if(returnfalse != 'true')
            return false;

    });

And other submit event;

$('#registerForm').submit(function(){
   alert('this Work...');
});

These two events works when i #registerForm submit. But i write return false above event.

Why is it works the second event ?

Upvotes: 3

Views: 6979

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

two consideration:

1) you should call stopImmediatePropagation() on the event to prevent the alert ( http://jsfiddle.net/R7uwa/ ) (if i remeber correctly return false equals to .preventDefault() and stopPropagation(). So no alert in this case:

$('form').submit(function(e){
    e.stopImmediatePropagation();
    return false;
});


$('form').submit(function(){
    alert('hi');
});

2) events binded in this way are executed in the order you bind them, so you should bind first your validation so that stopping the propagation works ( http://jsfiddle.net/R7uwa/1/ ). But if you look at this question jQuery event handlers always execute in order they were bound - any way around this? you can see that there is a workaround for this.

In this case you would hav an alert

$('form').submit(function(){
    alert('hi');
});


$('form').submit(function(e){
    e.stopImmediatePropagation();
    return false;
});

Upvotes: 5

Epuri
Epuri

Reputation: 300

return false basically prevents default browser behavior of the event in jQuery.

In the first code example return false will make sure to avoid default browser's form submit action but it will not avoid calling of multiple methods on single event.

As you are binding two methods on single form submit event, it will call both the methods one after other and first method will make sure to avoid browser's default submit action.

Upvotes: 0

Related Questions