Jquery multi submit event

I have coded a global mini-form for jQuery. It's 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 another dispatch event;

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

      

These two events work when I #registerForm

submit. But I am writing return false above the event.

Why does this work in the second case?

+3


source to share


2 answers


two considerations:

1), you must call stopImmediatePropagation () on the event to prevent the warning ( http://jsfiddle.net/R7uwa/ ) (if I return correctly, false equals .preventDefault () and stopPropagation (). So in this case no warnings:

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


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

      



2) events bound in this way are executed in the order in which you bind them, so you need to bind your validation first to stop propagating ( http://jsfiddle.net/R7uwa/1/ ). But if you look at this question , jQuery event handlers are always executed to be bound - is there any way to get around this? you can see there is a workaround for this.

In this case, you will have a warning

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


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

      

+4


source


return false

basically prevents the default browser behavior in jQuery.

In the first code example, you return false

will need to avoid the browser's default form submit action, but that will not avoid calling multiple methods in the same event.



Since you bind two methods in the submit event of one form, it will call both methods one after the other, and the first method will avoid the default submit action in the browser.

0


source







All Articles