0

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);
    }
}
4
  • 5
    The approach is OK, see developer.mozilla.org/pl/docs/DOM/element.onclick Can you create a demo of your problem on jsfiddle? Commented Aug 29, 2013 at 11:18
  • 1
    There is nothing obviously wrong with your code. Any JS errors? Commented Aug 29, 2013 at 11:18
  • 1
    It seems already working fine... Check it out..jsfiddle.net/3VXrF Commented Aug 29, 2013 at 11:21
  • Caveats: 1. default button type is submit (except in older IE due to bugs), so because you don't return false from the event handler, if the button is in a form, the form will be submitted afterwards. Also setting value on the button does nothing (except in older IE due to bugs); if you want to add text to the button then append a text node to its content, or otherwise use an <input type="button"> where value does correctly affect the text. But otherwise yeah... no obvious problem with calling the handler. Commented Aug 29, 2013 at 11:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or assign the handler function to the first argument of createButton, and use that when adding the handlers instead of writing duplicate code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.