user2807357
user2807357

Reputation: 49

avoid function closure in javascript

I want to link a callback to each input (type text) with class 'liveVariable':

$(".liveParameter").keyup(function(){
    var callBackString= 'skp:change-'+$(this).attr('id')+'@'+$(this).attr('value');
    window.location = callBackString;               
});

However, this gives me a strange error. The value passes is the initial value of the input field (every time the event is fired).

I don't understand why this doesn't work. I dont think I have a closure, the local variable callBackString is created in the called function. So it should be created every time over?

How can I solve this in an elegant manner? (I would not like to create a call for each input field, cause I have many live parameters..)

Upvotes: 0

Views: 859

Answers (2)

Chris Kempen
Chris Kempen

Reputation: 9661

Try changing:

var callBackString= 'skp:change-'+$(this).attr('id')+'@'+$(this).attr('value');

...to:

var callBackString= 'skp:change-'+$(this).attr('id')+'@'+$(this).val();

More detail on the .val() function can be found on the jQuery docs website here.

Edit:

For the sake of elegance, performance, and comment contribution, the following solution would ultimately be the best:

$(".liveParameter").keyup(function(){
    var input = $(this);
    var callBackString = 'skp:change-' + input.attr('id') + '@' + input.val();
    window.location = callBackString;
});

Upvotes: 1

Paul Rad
Paul Rad

Reputation: 4882

Change in your code

$(this).attr('value'); // get the initial value

$(this).val(); // get the current and updated value

http://jsfiddle.net/FjgLB/

Upvotes: 1

Related Questions