You can set it as attribute
txt_box.Attributes.Add("onchange", "myFunction(this);");
Also change your function to accept text box as parameter
function myFunction(control) {
alert(control.id);
}
if you need to get sum of textbox values, you can set class name for textboxes from codebehind as below
protected void Button1_Click(object sender, EventArgs e)
{
Table table = new Table();
table.ID = "Table1";
PlaceHolder1.Controls.Add(table);
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
row.ID = "Row_" + i;
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i ;
tb.CssClass = "sum";
cell.Controls.Add(tb);
tb.Attributes.Add("onchange", "myFunction();");
row.Cells.Add(cell);
table.Rows.Add(row);
}
}
then you can use find control by class name and calculate the sum as below
function myFunction() {
var sum = 0;
var elements = document.getElementsByClassName("sum");
for (var i = 0, length = elements.length; i < length; i++) {
if (elements[i].value) {
sum = sum + (parseInt(elements[i].value) || 0);
}
}
document.getElementById('<%= TextBox1.ClientID%>').value = sum;
}