asawyer
asawyer

Reputation: 5

Why does this javascript throw an undefined error?

I'd like to define my own onblur event for all text boxes in an application so that I can strip all high ascii values, so I wrote a script that runs on an asp.net master page that runs per page load, overriding all text box / area onblur events, and storing a copy of the old event.

The new event then called the old event so it wouldn't break existing events across the forms.

It worked fine until a page defined an onblur like: onblur="func(this)" When the original event fires the 'this' point doesn't seem to point to the sender control any longer.

Pastebin link with 2 simple examples

So would anyone be able to point me towards a better way to accomplish this?

Thanks!

Upvotes: 0

Views: 363

Answers (1)

Shtong
Shtong

Reputation: 1787

To call a function dynamically while controlling the value of this, use func.apply instead of a standard call. For example instead of

myStoredFunc(arg1, arg2)

use :

myStoredFunc.apply(this, arguments);

This way the value of the this variable will be correctly passed to the called function, thanks to apply's first argument. The second argument allows you to specify the parameter values (here I pass all the current function's arguments to the called function).

Upvotes: 1

Related Questions