neanderslob
neanderslob

Reputation: 2703

Passing variables to function using .on()

I have a text input field with its own class: .my_ids. I'm trying to write a script with jquery so that every time the input changes, it calls a particular function. This is easy enough if I don't try to pass a variable to the function:

$(document).on('change','.my_ids', testfunc);
function testfunc(){
    alert("good");
}

The function sends me an alert every time the input changes; works just fine.

However if I try to pass a variable to the alert function like so:

$(document).on('change','.my_ids', testfunc("hereismyvariable"));
function testfunc(myvariable){
    alert(myvariable);
}

it sends the alert when the document loads and then doesn't alert when the input changes. What might I be missing?

Upvotes: 2

Views: 79

Answers (3)

Ram
Ram

Reputation: 144709

() operator call the functions, so the returned value of the function is set as the handler, which doesn't seem to be what you want. Other answers suggest several solutions. Another option is using the data argument:

$(document).on('change', '.my_ids', "hereismyvariable", testfunc);

function testfunc(event) {
    console.log(event.data); // "hereismyvariable"
}

The data argument can be anything. data property of the event object refers to the passed value.

Upvotes: 1

orhanhenrik
orhanhenrik

Reputation: 1415

Here you are passing a function: $(document).on('change','.my_ids', testfunc);
Here you are passing the return value of a function: $(document).on('change','.my_ids', testfunc("hereismyvariable"));
Because testfunc("hereismyvariable") = undefined(No return value), you add an event handler with an undefined function.

Upvotes: 2

mildog8
mildog8

Reputation: 2154

You would do this

$(document).on('change','.my_ids', function() {
  testfunc("hereismyvariable");
});

Or you could do this

$(document).on('change','.my_ids', testfunc("hereismyvariable"));

function testfunc(myvariable){
  return function() {
    alert(myvariable);
  }
}

Upvotes: 1

Related Questions