开发者

Trigger the change event of a textbox in jQuery

I have an asp:TextBox with asp:RegularExpressionValidator to validate if it's a number. Obviously an onchange event will be attached to this textbox while rendering. Also I add a change event at $(document).ready to make some calculation when the value is changed.

<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. But the asp.net js throws an error. I traced in the js:

   function ValidatorOnChange(event) {
       ...
   }

and found that all of event.fromElement,event.toElement,event.srcElement are null which causes the exception. Did I do something wrong? Any solutions? Thanks.

EDIT

It's proved to开发者_如何学C be a MS bug, working fine in ASP.NET 4 vs2010.


Including Pointy's point (I crack myself up) about ID, you can re-write it like this:

$(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.


Pack your calculations in a function and call it on ready event instead of triggering a change:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜