user2435645
user2435645

Reputation: 3

Javascript / Ajax - onchange event for dynamically added row

I have a HTML table and i can add a new row to that table using javascript. I want to call a javascript (Ajax) function using the onchange event for each of the cells on the table. `

<script type="text/javascript" src="nextTest.js"></script>
    <SCRIPT language="javascript">
            function addRow(tableID) {

            var table = document.getElementById(tableID);

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

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

            var cell2 = row.insertCell(1);
            var element2 = document.createElement("input");
            element2.type = "text";
            element2.name = "txtbox[]";
        element2.onchange = nexttest();
            cell2.appendChild(element2);

    }

    </SCRIPT>

</HEAD>
<body>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<TABLE id="dataTable" width="350px" border="1">
    <TR>
        <TD> 1 </TD>
        <TD> <INPUT type="text" /> </TD>
    </TR>
</TABLE>

</body>
</html>`

When i press the button, a new row is added and the onchange event is fired. What i want to do is when ever someone enters data into those new cells, i want the onchange event to fire. The event is called 'nextTest' and it is stored in an external file.

When i insert the new row, the event fires, but if i update one of the cells, nothing happens. What am i doing wrong?

Thanks in advance

Upvotes: 0

Views: 3920

Answers (2)

Diode
Diode

Reputation: 25165

    function nexttest(evt){
        alert(evt.target.value);
    }

    function addRow (tableID) {

        var table = document.getElementById(tableID);

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

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

        var cell2 = row.insertCell(1);
        var element2 = document.createElement("input");
        element2.type = "text";
        element2.name = "txtbox[]";
        element2.onchange = nexttest; // give a valid function identifier here .
        cell2.appendChild(element2);

    }

http://jsbin.com/iropam/2/edit

Upvotes: 0

Dr.Molle
Dr.Molle

Reputation: 117354

you must assign a function, not a function-call(except the called function returns another function).

Omit the parentheses:

element2.onchange = nexttest;

Upvotes: 1

Related Questions