如何使onchange事件发生在ASP.NET的代码隐藏中? [英] how to make onchange event happened in code-behind in ASP.NET?

查看:50
本文介绍了如何使onchange事件发生在ASP.NET的代码隐藏中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文本框Mytbx,并且我有一个用于onchange事件的javascript.我将其连接到Page_Load事件中的代码中,例如:

Suppose I have a textbox Mytbx and I have a javascript for its onchange event. I hook it up in code behind in Page_Load event like:

Mytbx.Attributes.Add("onchange", "test();")

然后,我更改了此文本框的代码后文本,例如(例如在按钮单击事件中):

Then I changed the text in code-behind for this textbox like (in a button click event for example):

Mytbx.Text = MyValue

我希望触发onchange事件.但实际上不是.当我单击按钮更改Mytbx的值时,什么都没有发生.

I expect onchange event fired. but actually, it's not. When I click on the button to change value for Mytbx, nothing happening.

如何解决此问题?

推荐答案

仅当您直接键入内容并离开文本框时,onchange才会在客户端触发.因此,当您在后面的代码中设置文本框值时,什么也不会发生.

onchange will only be triggered on client side when you directly type something and leave the textbox. So nothing will happen when you set the textbox value in code behind.

如果要在客户端处理文本更改事件:

If you want to handle the text change event on client side:

<script>  
     function test(txt){
         alert(txt.value);
     };
</script>

<asp:TextBox ID="txt" runat="server" onchange="test(this);"></asp:TextBox>

如果要在服务器端处理文本更改事件,则可以执行以下操作:

If you want to handle text change event on server side, you could do this:

HTML:

<asp:TextBox ID="txt" runat="server" OnTextChanged="txt_OnTextChanged" AutoPostBack="true"></asp:TextBox>

CS:

protected void txt_OnTextChanged(object sender, EventArgs e)
{
     // Do something
}

这篇关于如何使onchange事件发生在ASP.NET的代码隐藏中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆