Execute a javascript function when textbox is populated in jQuery?

安稳与你 提交于 2019-12-11 03:38:39

问题


How do I execute a function in JavaScript when a text box is populated with text? The text box with be hidden from the user. It will be populated by a USB magnetic card swiper.

Pseudo code:

<script language="javascript" type="text/javascript">
    function MyFunction() {
        //execute this function when MyTxtBox is populated
    }
</script>
<asp:TextBox id="MyTxtBox" runat="server" Visible="false" />

回答1:


Seems like you're doing this when the page loads. If you are, this would work.

$(document).ready(function(){
   if($('#MyTxtBox').val().length > 0){
      MyFunction();
   }
});

If it's on change:

$(document).ready(function(){
   $('#MyTxtBox').change(function(){
       if($(this).val().length > 0){
          MyFunction();
       }
   });
});



回答2:


See munch's answer but use CSS to hide the text box as setting visible = false will result in the text box HTML not being rendered and therefore not being available on the client side.

<style type="text/css">
.USBBox
 {
     position: absolute;
     left: -999em; 
     overflow: hidden;
 } 
 </style>   
<asp.textbox id="MyTextBox" runat="server" CSSClass="USBBox" />

You can then use jQuery's class selector to acces the text box and not worry about name mangling:

%('.USBBox')

If you have a lot of elements on the page however you might be better accessing by id, in which case use the client id to avoid any name mangling issues:

$('#<%= MyTextBox.ClientID %>')

Update

Used CSS solution provided in this link to hide the textbox from the user. Updated the USBBox CSS class with correct solution as setting display:none caused javaScript issues.




回答3:


Attach to MyTxtBox's onChange event. You need to do a bit of ASP.NET to produce the appropriate ClientID for use in JavaScript, since ASP.NET will modify the MyTxtBox ID into something else.

<asp:TextBox id="MyTxtBox" runat="server" Visible="false" />
<script language="javascript" type="text/javascript">
    function MyFunction() {
        //execute this function when MyTxtBox is populated
    }

    document.getElementById("<%= MyTxtBox.ClientID %>").onChange = MyFunction;
</script>


来源:https://stackoverflow.com/questions/2002209/execute-a-javascript-function-when-textbox-is-populated-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!