简体   繁体   中英

c# asp.net textbox add oninput attribute dynamically

I want to make it so my dynamically added textbox calls a javascript function each time the value inside the textbox changes. This works by using the onInput attribute. Can I add this attribute dynamically, somewhere along those lines?

Textbox txt = new TextBox();
txt.ID = "test";
txt.Attrubute = onInput("jsfunction()");
form1.Controls.Add(txt);

or

txt.Attributes["onInput"] = "jsfunction()";

Thanks in advance :)

Edit:

This is my whole code snippet.

pholder.Controls.Add(new LiteralControl("<table>"));
for (int i = 0; i < dv_inputParameter.Count; i++)
{
    pholder.Controls.Add(new LiteralControl("<tr>"));
    pholder.Controls.Add(new LiteralControl("<td>"));
    Label lbl = new Label();
    lbl.Text = dv_inputParameter.Table.Rows[i][1].ToString() + " ";
    lbl.ID = "lbl_parameter" + i;
    pholder.Controls.Add(lbl);
    pholder.Controls.Add(new LiteralControl("</td>"));

    pholder.Controls.Add(new LiteralControl("<td>"));
    TextBox txt = new TextBox();
    String tb_id = "tb_parameter" + i;
    txt.ID = tb_id;
    txt.Attributes.Add("onkeyup", String.Format(@"var txt = document.getElementById({0}); var btn = document.getElementById('Btn_Start'); btn.disabled = (txt.value.trim().length == 0)", tb_id));
    pholder.Controls.Add(txt);
    pholder.Controls.Add(new LiteralControl("</td>"));
    pholder.Controls.Add(new LiteralControl("</tr>"));
}
pholder.Controls.Add(new LiteralControl("</table>"));

I am putting the label and textboxes inside a html table. The function is supposed to make the button with the ID "Btn_Start" clickable as soon as all textboxes have been filled out.

你可以用这个

txt.Attributes.Add("onkeyup", "alert('Key UP');");

try this

<script type="text/javascript">
           function keyUP()
           {
              alert('hi');
           }
  </script>

add this attribute for textbox

  txt.Attributes.Add("onKeyUp", "keyUP()")

This will give you alert whenever you enter any letter in your textbox.

如果要在文本框内的文本更改时调用函数,可以向文本框添加onchange属性。

txt.Attributes["onchange"] = "jsfunction()";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM