Ashutosh Kumar
Ashutosh Kumar

Reputation: 31

function not invoking in jQuery

I am using this function

$(function () {
    validateSignUp = function () {
        console.log("Validation running");
        em = $('#s_email').val();
        a = validateEmail(em);
        if (!a) {
            $('#s_email').css({ "border": "3px solid red" });
            $("#signup_comments").html("Please Enter a valid Email Address");
            return false;
        }
        else
            return true;
    };
    $("#mybutton").click(function () { console.log(validateSignUp) });
});

When I run above function, console prints the complete function as that is not a function and a variable.

Why it is not returning true or false as a function ? Why it is behaving like a variable ?

Upvotes: 0

Views: 52

Answers (2)

Beri
Beri

Reputation: 11620

validateSignUp is an reference to function, thus, you need to invoke this function, and then log the result, like so:

 $("#mybutton").click(function () { 
      var fnResult = validateSignUp() ;
      console.log(fnResult) 
 });

Secondly you need to execute this code, when mybutton button has been already added to DOM, otherwise jQuery will not add onClick event to it, as there will be zero elements at this time with this id. You can do it in two ways:

  1. wrap this function in onLoad event
  2. add defer attribute to it (it will execute script, when whole dom will be parsed).

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

You have to call the function,

 console.log(validateSignUp());

Here in your code, you are simply passing the function reference as a parameter to console.log(), so it is printing the primitive value (string) of that function reference aka an object.

Upvotes: 1

Related Questions