PuddingCat
PuddingCat

Reputation: 45

Can I create multiple onclick events dynamically?

For some reason I am unable to re-enable a button and go through all of the columns I have in a table with the same button. Can I create multiple onclick events for the button? The HTML itself is really just a button within a table.

   function focaccia(x){
     var table = document.getElementById("orderTable");
      var row = table.insertRow(0);

      var rem = document.createElement("button");
      var name = document.createTextNode("Remove");
      rem.appendChild(name);

      rem.onclick = function(){
        x.disabled = false;
        document.getElementById("orderTable").deleteRow(this);
        var table = document.getElementById("orderTable");
        var amount = 0;
        var tot;
        for(var x = 0; x < table.rows.length; x++){
         amount = amount + parseInt(table.rows[x].cells[1].children[0].value);
        }
        tot = amount * 9;
        document.getTotal.total.value = tot;
      }

      var num = document.createElement("input");
      num.size = 2;

      num.onchange = function(){

        var table = document.getElementById("orderTable");
        var amount = 0;
        var tot;
        for(var x = 0; x < table.rows.length; x++){
         amount = amount + parseInt(table.rows[x].cells[1].children[0].value);
        }
        tot = amount * 9;
        document.getTotal.total.value = tot;
      }

        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        cell1.innerHTML = "Focaccia";
        cell2.appendChild(num);
        cell3.appendChild(rem);
        x.disabled = true;
        num.value = 1;
        total = total + 9;
        document.getTotal.total.value = total;

}

Upvotes: 0

Views: 851

Answers (1)

Max Heiber
Max Heiber

Reputation: 15502

Yes, use addEventListener.

Instead of target.onclick=clickHandlerFunction;, use target.addEventListener('click', clickHandlerFunction);'

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

Note: The syntax for adding events using old Internet Explorer is different (target.attachEvent('onclick',handler)). If you need compatibility with old browsers, you can use both syntaxes, use jQuery's click or on functions or gator.js.

Upvotes: 1

Related Questions