Link to home
Start Free TrialLog in
Avatar of -Dman100-
-Dman100-Flag for United States of America

asked on

preventDefault is not preventing button from calling method in my class file

I have a button that preforms a search action on my page. I'm using jquery to do a simple validation on a zip code for 5 digits. I'm using preventDefault to stop my button from running the search if the zip code is not valid. However, the preventDefault method does not seem to be working. It still runs the search even if the zip code is not validated correctly.

Here is my jquery code:

    var j$ = jQuery.noConflict();

    j$(document).ready(function() {
        var searchButton = j$('[id$=theFilterButton]');
        var isValid = true;
        searchButton.click(function(e) {
            var zip = j$('[id$="ZipCodeFilter"]').val();
            var reg = /^[0-9]+$/;
            if((zip.length) < 5 || (zip.length) > 5 ) {
                isValid = false;
                console.log("zip code length is not 5");
            }
            if (!reg.test(zip)){
                isValid = false;
                console.log("zip is not digits");
            }
            if(!isValid) {
                console.log("zip is not valid. Stop processing!!!!");
                e.preventDefault();
            }
        });     
    });

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

replace :
e.preventDefault();
by :
e.stopImmediatePropagation();

http://api.jquery.com/event.stopimmediatepropagation/
Avatar of -Dman100-

ASKER

Hi leakim971, thanks for replying to my post.  I just tried e.stopimmediatePropagation(); and that didn't work either.  The button continues to run my search regardless.
I did a console.log(isimmediatePropagationStopped());

and I got this in my log:

zip code length is not 5
zip is not valid. Stop processing!!!!
true
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Is the searchButton a submit or just a button?  If it's a submit, you may want to use searchButton.submit instead of searchButton.click.