O P
O P

Reputation: 2365

Pass variable as parameter in jQuery

HTML

<input type="text" id="test" />

<span>0</span>

jQuery

var input = $('input#test');

input.bind('keyup', function() {
    doThis();
});

input.on('input', function() {
    doThis();
});

function doThis() {
    var wordCounts = {};
    var matches = this.value.match(/\b/g);
    wordCounts[this.id] = matches ? matches.length / 2 : 0;
    var finalCount = 0;
    $.each(wordCounts, function(k, v) {
        finalCount += v;
    });
    $('span#word-count').text(finalCount);
}

jsFiddle: http://jsfiddle.net/YJVPZ/265/

Right now doThis() doesn't even work. If I was to wrap the contents of doThis() with input.bind('keyup', function() { ... } it will work just fine. I know it is because it's using an undefined this. How can I pass the variable input as a parameter?

Is there any way to use .bind and .on together to call for the same function instead of two separate instances as I have now?

Upvotes: 0

Views: 937

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70199

input.bind('keyup input', doThis);

Fiddle

By passing a function to .bind/.on jQuery automatically sets the this reference inside of the handler to the element that triggered said event handler (in this case, #test).


To set the this reference manually, which is unnecessary in this case, you'd use Function.call / Function.apply:

input.bind('keyup input', function() {
    //in this scope, `this` points to `#test`
    doThis.apply(this, arguments); //sets `this` inside of this `doThis` call to
                                   //the same `this` of the current scope.
});

We apply arguments so that doThis also receives the Event object which is passed to event handlers. Not necessary in this specific use case, but it is useful when proxying an event handler that needs to access the arguments passed to the original handler.


Side-note: For your code to work, you should move it to the end of the body or wrap your code inside of a DOM ready handler, that is, put it inside of $(function(){/*code here*/});

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

try this -

input.on('input keyup', doThis);

Upvotes: 0

Related Questions