简体   繁体   English

在jQuery中触发文本框的change事件

[英]Trigger the change event of a textbox in jQuery

I have an asp:TextBox with asp:RegularExpressionValidator to validate if it's a number. 我有一个带有asp:RegularExpressionValidator的asp:TextBox来验证它是否是数字。 Obviously an onchange event will be attached to this textbox while rendering. 显然,渲染时会将onchange事件附加到此文本框。 Also I add a change event at $(document).ready to make some calculation when the value is changed. 另外,我在$(document).ready添加了一个change事件,准备在值更改时进行一些计算。

<asp:TextBox id="myText" runat="server" />
<asp:regularexpressionvalidator id="myRev" ControlToValidate="myText" runat="server">*</asp:regularexpressionvalidator>

$(document).ready(function(){
    $('[id$=myText]').bind('change',function(){
           //do something
    }).change();      //force the change event at the very beginning
});

My function will be executed later than the .net generated js because of the register time. 由于注册时间的原因,我的函数将在.net生成的js之后执行。 But the asp.net js throws an error. 但是asp.net js抛出错误。 I traced in the js: 我追踪到js:

   function ValidatorOnChange(event) {
       ...
   }

and found that all of event.fromElement,event.toElement,event.srcElement are null which causes the exception. 并发现所有event.fromElement,event.toElement,event.srcElement为null都会导致异常。 Did I do something wrong? 我做错什么了吗? Any solutions? 有什么办法吗? Thanks. 谢谢。

EDIT 编辑

It's proved to be a MS bug, working fine in ASP.NET 4 vs2010. 事实证明,这是一个MS错误,可以在ASP.NET 4 vs2010中正常工作。

Including Pointy's point (I crack myself up) about ID, you can re-write it like this: 包括Pointy关于ID的观点(我自己说了),您可以这样重写它:

$(function(){
  $('#<%=myText.ClientID%>').change(function() {
    //stuff
  }).triggerHandler('change');
});

Without seeing exactly how your other event is attached, .triggerHandler() would be my best suggestion, as the event doesn't bubble up for capture by the .Net handler. 在没有确切了解其他事件如何附加的情况下, .triggerHandler()是我的最佳建议,因为该事件不会冒泡被.Net处理程序捕获。

Pack your calculations in a function and call it on ready event instead of triggering a change: 将您的计算打包到一个函数中,并在ready事件中调用它,而不是触发更改:

$(document).ready(function(){
    $('[id$=myText]').bind('change',function(){
           doCalc(); // or doCalc(this) or whatever you need
    });
    doCalc();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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