jameshwart lopez
jameshwart lopez

Reputation: 3151

preventDefault and return false; if i add if else statement

I have this js code

$(document).ready(function(){

    $("#frm_registration").submit(function(event){
        var submit = false;

        termsIsChecked      = $("#user_terms_of_service").is(":checked");
        uEmail              = $("#user_email").val();
        uPassword           = $("#user_password").val();
        uConfirmPassword    = $("#user_password_confirmation").val();
        uFirstName          = $("#user_firstname").val();
        uLastName           = $("#user_firstname").val();
        uContactNumber      = $("#user_firstname").val();
        uOtherInformation   = $("#user_firstname").val();


        // if(uPassword.length === 0){
        //    uPassword.after("<p>Password can't be blank</p>");
        //    submit = false;
        // }

        if(submit === false){
            event.preventDefault(); 
        }
    });
});

if i uncomment the if block the form will submit event if i change event.preventDefault(); to return false; it still won't work if the if block is uncommented. my problem is why jquery is reponding like this, if i add if statement the preventDefault and return false; wont work but if i remove if statement or comment it out the preventDefault and return false; will work.can someone explain why its like this

Upvotes: 0

Views: 3619

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

The problem is uPassword is not a jQuery object, it is a string so there is no method called after for String object. Which should give you an error like Uncaught TypeError: uPassword.after is not a function in your browser console.

$("#user_password").after("<p>Password can't be blank</p>");

Also you will have to initialize submit with the value false like

$(document).ready(function () {

    $("#frm_registration").submit(function (event) {
        var submit = true;

        termsIsChecked = $("#user_terms_of_service").is(":checked");
        uEmail = $("#user_email").val();
        uPassword = $("#user_password").val();
        uConfirmPassword = $("#user_password_confirmation").val();
        uFirstName = $("#user_firstname").val();
        uLastName = $("#user_firstname").val();
        uContactNumber = $("#user_firstname").val();
        uOtherInformation = $("#user_firstname").val();


        if (uPassword.length === 0) {
            $("#user_password").after("<p>Password can't be blank</p>");
            submit = false;
        }

        if (submit === false) {
            event.preventDefault();
        }
    });
});

Demo: Fiddle

Upvotes: 2

Related Questions