Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 434
s3yfullah Avatar asked Dec 30 '25 22:12

s3yfullah


1 Answers

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;
});
like image 82
Nicola Peluchetti Avatar answered Jan 02 '26 10:01

Nicola Peluchetti