json1 json1 - 3 months ago 9
Javascript Question

Why isnt my value being returned in jquery?

I have created a

validate()
function in JavaScript, and when I invoke the method it returns
undefined
.... everything in my code looks right to me, why is it doing that?

function validate() {
var __self = this;
__self.is_valid = true;

$(document).on("click", "#login,#create_account", function() {
var email = $("#email").val(),
password = $("#password").val();

if (email == "") {
$("#email-err-msg").removeClass("hidden").html("Enter an email address");
__self.is_valid = false;
} else {
$("#email-err-msg").addClass("hidden")
}

return __self.is_valid;
});
}

(function logUser() {
$(document).on("submit", "form", function() {
var action = $(".action").attr("data-account-action");

console.log(validate());

if (!validate()) {
return false;
}
});
})();

Answer

Your validate function never returns anything, so the result of calling it is always undefined. You have a callback to an event handler that you define within it, and you have a return statement in that, but none in validate.

It's not clear why you are hooking up an event handler every time the user tries to submit a form. I would suggest not doing that. Perhaps something like:

function validate() {
    var is_valid = true;

    var email = $("#email").val(),
        password = $("#password").val();

    if (email == "") {
        $("#email-err-msg").removeClass("hidden").html("Enter an email address");
        is_valid = false;
    } else {
        $("#email-err-msg").addClass("hidden")
    }

    return is_valid;
}

(function logUser() {
    $(document).on("submit", "form", function() {
        var action = $(".action").attr("data-account-action");

        return validate();
    });
})();

I've removed the click event handler as I couldn't see that there was any reason for it, removed the global variable __is_valid,1 and returns the result of calling validate directly from the submit handler (since returning true is harmless).


1 Why was it a global variable? Because you were calling validate like this: validate(), which means that within the call, this refers to the global object (unless you're using strict mode, in which case it would be undefined; but I know you aren't because you said it returned undefined rather than throwing an error). Adding properties to the global object creates global variables.