vicky
vicky

Reputation: 21

How do I add a click handler to a new element when I create it?

How do I add a click handler to a new element when I create it? This is what I have tried, but it does not work as expected:

DeCheBX = $('MyDiv').insert(new Element('input', {
    'type': 'checkbox',
    'id': "Img" + obj[i].Nam,
    'value': obj[i].IM,
    'onClick': SayHi(this)
}));
document.body.appendChild(DeCheBX);
DeImg = $('MyDiv').insert(new Element('img', {
    'id': "Imgx" + obj[i].Nam,
    'src': obj[i].IM
}));
document.body.appendChild(DeImg);
}
SayHi = function (x) {
    try {

        if ($(x).checked == true) {
            alert("press" + x);
        }

    }
    catch (e) {
        alert("error");

Upvotes: 1

Views: 511

Answers (5)

nahum silva
nahum silva

Reputation: 1

with prototype will something like this

$('id').observe('click',function(event){
      alert("make something cool");
}.bind(this))

or the second option

Element.observe('id',"click",function(){
    alert("make something cool");
}.bind(this))

both works... cheers =)

Upvotes: 0

Minimul
Minimul

Reputation: 4205

var myElem = new Element('input', {'type': 'checkbox','id': "Img" + obj[i].Nam,'value': obj[i].IM }).observe('click',sayHi);
$('MyDiv').insert(myElem);

SayHi = function () {
try {

    if (this.checked == true) {
        alert("press" + this);
    }

}
catch (e) {
    alert("error");

Upvotes: 0

plodder
plodder

Reputation: 2306

this will be window because that is the invoker of the onclick function.

bind will fix this if you are using prototype or other libraries but for those who want a native solution, you need to break up your code a little to simplify it:

var myElem = new Element('input', {
    'type': 'checkbox',
    'id': "Img" + obj[i].Nam,
    'value': obj[i].IM
}

myElem.onclick = function() {sayHi(myElem )};

DeCheBX = $('MyDiv').insert(myElem);

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532435

The way you are adding the handler, the function is actually being invoked when you create the element. When you write SayHi(this) it actually runs the function with the current value of this. What I'd suggest is wrapping the invocation of the handler into an anonymous function defined when you create the element. That way the SayHi code won't actually be executed until the click handler is invoked. Replace this:

'onClick': SayHi(this)

with

'onClick': function() { SayHi(this); } 

Upvotes: 2

robert
robert

Reputation: 5283

'onClick': SayHi.bind(this)

Hi there!

Just use '.bind' before your params! An event handler has to be a function, not the return of your function. Create a functions that will have the params you want baked in by using .bind.

-Rob

Upvotes: 0

Related Questions