Search code examples
javascriptjqueryhtml-tabledynamic-tables

Javascript function call from HTML Table Cells


I have created one dynamic HTML table.We can add and delete rows for that table. I have tried to call one javascript function from cells but that call is not happening.How can i call method from my addrow method

addRow() function code given below

    function addRow(tableID) {

            var table = document.getElementById(tableID);

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

            var cell0 = row.insertCell(0);
            var element0 = document.createElement("input");
            element0.type = "checkbox";
            element0.name="chkbox[]";
            cell0.appendChild(element0);

            var cell1 = row.insertCell(1);
            cell1.innerHTML = rowCount + 1;

            var cell2 = row.insertCell(2);
            var element2 = document.createElement("input");
            element2.type = "text";
            element2.name = "txtbox[]";
            element2.onchange = "myChangeFunction(this)"; // calling Javascript function
            cell2.appendChild(element2);

}

looking forward for suggestions


Solution

  • To achieve this attach the event using the addEventListener() method, like this:

    element2.addEventListener('change', myChangeFunction);
    

    Then in your myChangeFunction(), the this keyword will refer to the element that raised the event. Try this:

    function addRow(tableID) {
      var table = document.getElementById(tableID);
    
      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);
    
      var cell0 = row.insertCell(0);
      var element0 = document.createElement("input");
      element0.type = "checkbox";
      element0.name = "chkbox[]";
      cell0.appendChild(element0);
    
      var cell1 = row.insertCell(1);
      cell1.innerHTML = rowCount + 1;
    
      var cell2 = row.insertCell(2);
      var element2 = document.createElement("input");
      element2.type = "text";
      element2.name = "txtbox[]";
      element2.addEventListener('change', myChangeFunction);
      cell2.appendChild(element2);
    }
    
    function myChangeFunction() {
      console.dir(this);
    }
    
    addRow('foo');
    <table id="foo"></table>

    Also note that, as you've tagged the question with jQuery, you can massively simplify this code:

    function addRow(tableID) {
      var $table = $('#' + tableID);
      var $tr = $('<tr><td><input type="checkbox" name="chkbox[]" /></td><td>' + ($table.find('tr').length + 1) + ' <input type="text" name="txtbox[]" class="txtbox" /></tr>').appendTo($table);
    }
    
    $('table').on('change', '.txtbox', function() {
      console.dir(this);
    });
    
    addRow('foo');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="foo"></table>