user3682205
user3682205

Reputation: 241

cannot add onclick event to dynamically created button

I have a script that is meant to dynamically create row items. My problem is the creation of the last cell item, a button. I have tried using onclick, setAttribute and attachEvent. But either the button is created or the onclick event is launched in the addGarageRow() function which creates the button and not the onclick event of the created button itself

  function addGarageRow(tableID)
   {
     var table=document.getElementById(tableID);

     rownum = rownum + 1;
     var rowCount=table.rows.length;
     var row=table.insertRow(rowCount);

     var cell1=row.insertCell(0);
     var element1=document.createElement("input");
     element1.type="checkbox";
     element1.name="chk[]";

     cell1.appendChild(element1);


     var cell2=row.insertCell(1);
     var element2=document.createElement("input");
     element2.type="text";
     element2.id=rownum;
     element2.name="garage_for[]";

     cell2.appendChild(element2);

    var cell3=row.insertCell(2);
    var element3=document.createElement("input");
    element3.type="text";
    element3.id="amount"+rownum;
    element3.name="garage_amount[]";
    cell3.appendChild(element3); 

    var cell4=row.insertCell(3);
    var element4=document.createElement("input");
    element4.setAttribute("type", "button");
    element4.id=rownum;
    //element4.name="voucher";
    //element4.onclick = alert("test");
    //element4.setAttribute("onClick", alert("test");
    //element4.attachEvent('OnClick',Hi());
    cell4.appendChild(element4);

 }

Upvotes: 0

Views: 652

Answers (2)

Bram Bogaerts
Bram Bogaerts

Reputation: 76

You have to wrap the function you would like to be executed when the onclick event fires inside a function block. Check it out here: http://jsfiddle.net/qbhfdkq3/

Upvotes: 2

Bwaxxlo
Bwaxxlo

Reputation: 1880

The handler should be wrapped in a function. i.e:

element4.onclick = function(){
   alert("test");
}

Upvotes: 3

Related Questions