0

I try to call a function in jquery with parameter such that

$(document).ready( function() {
    $('#id_pros').bind('change', wordCounter('id_pros_wordCountLabel') );
});

function wordCounter(item){
    ....
}

If I don't pass parameter id_pros_wordCountLabel it works great but now it didn't call wordCounter.

Which part is wrong with my code ?

Thanks

1
  • 1
    Bind expexts you to pass a reference to a function (or directly, a anonymous function) but instead you execute the function during the "bind" process, which returns undefined, so nothing is bound. Commented Jun 17, 2011 at 12:35

2 Answers 2

1

.bind() expects a function argument, like this:

$('#id_pros').bind('change', wordCounter);

Note how there are no parentheses on wordCounter. This means that it's a reference to a function, and not an invocation of a function — which is what happens when you add parentheses. Use an anonymous function to solve the problem:

$('#id_pros').change(function ()
{
    wordCounter('id_pros_wordCountLabel');
});

(I also changed .bind('change', ...) to .change(...) which is equivalent but more concise.)

Sign up to request clarification or add additional context in comments.

Comments

1

The correct way to do it is:

$(document).ready( function() {
    $('#id_pros').bind('change', function() {
        wordCounter('id_pros_wordCountLabel');
    });
});

Your own code passes the return value of wordCounter (which is called on the spot, and not when the change event fires) to bind. bind expects to receive a function, and wordCounter probably returns something else, so when the change event fires you don't see anything happen.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.