Erwin
Erwin

Reputation: 111

How to use a Function in Jquery?

I'm Trying to make a function in jQuery

function Formulier1() {
     var usr_length = $(this).val().length;

     if(usr_length == 0){
          error.push("- Er is geen gebruikersnaam ingevuld." + "</br>");
     }
}

but when im calling the function

$("#gebruikersnaam").focusout(function(){ 
     Formulier1();
});

They dont can't see the further code

$("input").focusout(function(){
     alert("Doesnt comes here");
     $("#error").html('');
     if(error == ""){
          //do something
     }else{
          $('#error').append(error);

          error = [""];
     }
});

I forgot something to do? or im doing something wrong? when I put the code without an extra function but put it into the gebruikersnaam focusout it works fine.

I want to use the code Formulier1 more then once thats why I wanted into an extra function!

Upvotes: 1

Views: 54

Answers (3)

Balachandran
Balachandran

Reputation: 9637

You just bind function name in callback

$("#gebruikersnaam").focusout(Formulier1);

OR use call function if you have to pass more arguments

$("#gebruikersnaam").focusout(function(){ 
     Formulier1.call(this);
});

Upvotes: 2

Mario Araque
Mario Araque

Reputation: 4572

You need to pass $(this) as a paremeter in your Formulier function.

For example:

$("#gebruikersnaam").focusout(function(){ 
    Formulier1($(this)); 
});

function Formulier1($this) {
    var usr_length = $this.val().length;

    if(usr_length == 0){
        error.push("- Er is geen gebruikersnaam ingevuld." + "</br>");
    }
}

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

You need to pass the object to that function

$("#gebruikersnaam").focusout(function(){ 
            Formulier1(this);
});

then your function will be

function Formulier1(obj) {
     var usr_length = $(obj).val().length;

     if(usr_length == 0){
          error.push("- Er is geen gebruikersnaam ingevuld." + "</br>");
     }
}

Upvotes: 0

Related Questions