0

This is my first question on this awesome community.

I am using this javascript code to build a dynamic table:

    function addRow(tableID) {

        var table = document.getElementById(tableID);

        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 = "chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);          
        var element2 = document.createElement("input");
        element2.type = "text";
        element2.name = "txtbox[]";
        element2.onkeypress = "this.style.width = ((this.value.length + 1) * 8) + 'px'";
        cell2.appendChild(element2);


    }

And following html code to print it:

       <table id="dataTable" style="width: 300px;" border="0">
            <tr>
                <td ><input type="checkbox" name="chk"  /></td>

                <td  <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"> </td>
            </tr>
        </table>

My problem is that- I want my text input field to be dynamically expending, but due to using 'document.createElement("input");' in the Javascript, only the first text input field expends dynamically rest

Abhijeet
  • 3
  • 2

2 Answers2

0

You can define your expanding function and reuse it later, like this:

expandTextBox = function (tb) {
    tb.style.width = ((tb.value.length + 1) * 8) + 'px';
}

And when you create element:

var element2 = document.createElement("input");
element2.onkeypress = function() { expandTextBox(element2); };

And in html:

<input id="txt" type="text" onkeypress="expandTextBox(this)">

See the Fiddle

Tony
  • 6,917
  • 3
  • 21
  • 33
0

When add events to dynamically created elements in javascript, you must define the event code as a function not as a string! So, modify your addRow function to this:

    ...
    element2.onkeypress = function(){this.style.width = ((this.value.length+1)*8)+'px'};
S.Serpooshan
  • 6,368
  • 2
  • 29
  • 53