javascript events
-
Hi, I have a small HTML with a button and a handler object which is likely to catch the button's onclick event. When I try to click the button it says "this.button.id is null or not an object". If I do onclick="objHelper.buttonClick" in the "input type=button" tag instead it works fine. What is the right solution? Here is my code: function helper() { var button; this.setButton = function(tobjButton) { this.button = tobjButton; this.button.onclick = this.buttonClick; }; this.buttonClick = function() { alert(this.button.id); }; } var objHelper = new helper(); function init() { objHelper.setButton(document.all("btnButton")); } Thanks: (K)
-
Hi, I have a small HTML with a button and a handler object which is likely to catch the button's onclick event. When I try to click the button it says "this.button.id is null or not an object". If I do onclick="objHelper.buttonClick" in the "input type=button" tag instead it works fine. What is the right solution? Here is my code: function helper() { var button; this.setButton = function(tobjButton) { this.button = tobjButton; this.button.onclick = this.buttonClick; }; this.buttonClick = function() { alert(this.button.id); }; } var objHelper = new helper(); function init() { objHelper.setButton(document.all("btnButton")); } Thanks: (K)
Hi there, When I try to click the button it says "this.button.id is null or not an object" At the time the
buttonclick
function executes, thethis
keyword refers to thebutton
object, not theobjHelper
. And thebutton
object certainly does not contain anybutton
member, so thethis.button
is undefined, then it should raise the error when you are accessing thethis.button.id
. If I do onclick="objHelper.buttonclick" in the "input type=button" tag instead it works fine Now you invoke the functionbuttonclick
of theobjHelper
object, so thethis
keyword in the function should refer to theobjHelper
, and as a result it should be working as you expected. To work around, you can simply change a bit your sample code:this.buttonclick = function()
{
//alert(this.button.id);alert(this.id);
};