luciansvnc
luciansvnc

Reputation: 131

How to create a button with onclick with JavaScript?

I have a function that creates a couple of buttons. The problem is that the onclick attribute is not working. How can I use this attribute in JavaScript?

function querySuccess(tx, results) {
    var len = results.rows.length;

    for (var i=0; i<len; i++){
        var name = results.rows.item(i).name;

        var button = document.createElement("button");
        button.className = "buttons";
        button.value = name;
        button.onclick = function() {
            alert("assa");
        };

        var listIt = document.createElement("li");
        listIt.className = "item";
        listIt.appendChild(button);

        var favs = document.getElementById("favs");
        favs.appendChild(listIt);
    }
}

Upvotes: 0

Views: 157

Answers (1)

deostroll
deostroll

Reputation: 11995

The correct way of doing it...is calling addEventListener (in case of Mozilla/webkit browsers) or attachEvent (IE browsers).

function createButton(){
    var btn = document.createElement('button');
    btn.innerHTML = 'Click Me';
    if(btn.addEventListener)
        btn.addEventListener('click',function(){
            alert('hello');
        });
    else
        btn.attachEvent('click',function(){ alert('hello'); });
    document.body.appendChild(btn);
}

See http://jsfiddle.net/L2KD5/

Edit: Check the following link for a more generic implementation: https://gist.github.com/eduardocereto/955642

Upvotes: 1

Related Questions