简体   繁体   中英

Can't see the inf loop that i am making

For a school assignment I have to make a jQuery plugin. I am almost finished with it, but for some reason I really can't see, I end up with an infinite loop when I try to submit the form (which crashes Google Chrome). Here is the code:

console.log("starting plugin");
$(document).ready(init);

function init() {
    $('#password').on('keyup', clickHandler);
}
function clickHandler() {
    console.log("clickHandler");
    $.fn.passwordCheck();

}
(function () {
    var settings = {
        passwordInput: $('input[type="password"]'),
        passwordNeededLength: 8,
        passwordStrenght: 2,
        errorMessageLoc: 'passwordinfomessage',
        messageLoc: '#passinfo'
    };
    var methods = {
        init: function () {
            console.log("started methods init");
            methods.checkStrength();
        },
        createMessages: function (status) {
            console.log("start function createmessages");
            var $messageLoc = $(settings.messageLoc);
            var $errormessage = settings.errorMessageLoc;
            $($messageLoc).css("display","inline-block");
            if (status === 1) {
                $("#passinfo").empty();
                $messageLoc.append("<p id='passwordLength' class=" + $errormessage + ">the password needs to be atleast " + settings.passwordNeededLength + " characters</p>");
                console.log("created message #1");
            } else if (status === 2) {
                $("#passinfo").empty();
                $($messageLoc).append("<p id='weak' class=" + $errormessage + ">The password is to weak to be accepted, please try adding some characters</p>");
                console.log("created message #2");
            } else if (status === 3) {
                $("#passinfo").empty();
                $($messageLoc).append("<p id='good' class=" + $errormessage + ">The password is the password is of good strength, u can try adding some numbers and capital letters</p>");
                console.log("created message #3");
            } else if (status === 4) {
                $("#passinfo").empty();
                $($messageLoc).append("<p id='strong' class=" + $errormessage + ">The password is strong</p>");
                console.log("created message #4");
            } else if (status === 5) {
                $("#passinfo").empty();
                $($messageLoc).append("<p id='submitButtonMessage' class=" + $errormessage + ">Something is wrong with your password</p>");
                console.log("created message #5");
            }
        },
        checkStrength: function () {
            console.log("start function checkStrength");
            var strength = 0;
            if (settings.passwordInput.val().length >= settings.passwordNeededLength) {
                strength += 1;
                console.log("password length is accept");
                if (settings.passwordInput.val().length >= 25) strength += 2;

                if (settings.passwordInput.val().match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  strength += 1;

                if (settings.passwordInput.val().match(/([a-zA-Z])/) && settings.passwordInput.val().match(/([0-9])/))  strength += 1;

                if (settings.passwordInput.val().match(/([!,%,&,@,#,$,^,*,?,_,~])/))  strength += 1;

                if (settings.passwordInput.val().match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;

                methods.checkStrengthResult(strength);
            }
            else {
                console.log(settings.passwordInput.val().length);
                console.log("not big");
                if (settings.passwordInput.val() == 0) {
                    console.log("just entered the site");

                } else {
                    $('.' + settings.errorMessageLoc).remove();
                    methods.createMessages(1);
                }
            }
        },
        checkStrengthResult: function (strength) {
            console.log("start function checkStrengthResult");
            console.log(strength);
            //if value is less than 2
            if (strength < 2) {
                console.log("password is to weak");
                methods.createMessages(2);
            }
            if (strength == 2) {
                console.log("password is good");
                methods.createMessages(3);
            }
            if (strength > 3) {
                console.log("password is strong");
                methods.createMessages(4);
                methods.checkPasswordStrength(strength)
            }
        }
        ,
        checkPasswordStrength: function (strength) {
            $( "#testform" ).submit(function( event ) {
                console.log( "Handler for .submit() called." );
                if (strength >= settings.passwordStrenght&& settings.passwordInput.val().length >= settings.passwordNeededLength){
                    console.log("is good");
                    console.log("i will submit");
                    $( "#testform" ).submit();
                    event.preventDefault();

                } else{
                    console.log("not good");
                    event.preventDefault();
                    methods.init();
                }
            });

//            console.log("stopt posting");
//            if (typeof strength == 'undefined'|| strength == 0) {
//                event.preventDefault();
//                console.log("strength was undifined");
//                methods.init()
//            } else {
//                if (strength >= settings.passwordStrenght&& settings.passwordInput.val().length >= settings.passwordNeededLength) {
//                    console.log("password is strong enhough");
//                    event.preventDefault();
//                } else {
//                    console.log("stoping submitting");
////                  console.log(strength);
//                    event.preventDefault();
//                    methods.createMessages(5);
//
//                }
//            }
////        }
        }
    };
    $.fn.passwordCheck = function (options) {
        console.log("start password check");
        if (options) {
            settings = $.extend(settings, options);
            console.log(options);
            console.log(settings);
        }

        $('#password').on('keyup', methods.init());
        $('#submitbutton').on('click', methods.checkPasswordStrength());

        return this;
    };
})(jQuery);

In the last method I tried something before, but I didn't get that working ether.

You are binding to submit, and then submitting the form again within the handler.

Change

$( "#testform" ).submit();

to

$( "#testform" )[0].submit();

This will perform a native form submit rather than triggering the submit event again.

I don't think it's an infinite loop, I think it's that your code is attaching a massive number of event handlers, and your browser crashes trying to handle all of these.

I would suggest getting some paper and drawing out where your code execution goes. It should only attach a given type of event to a given element once . If it does so more than once, you almost certainly have a problem!


EDIT: Reading Tom's answer, there is indeed an infinite loop! You should just not prevent the default event handler when the form is valid. e.preventDefault() should only be called if you want to stop the form from submitting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM