问题
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