ASP.Net Update Panel – Javascript Event – jQuery Click

I needed to add a onclick event to a textbox in asp.net to change it to remove text from a textbox onClick when it is clicked.
The normal code would look something like this:

1
<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
1
2
3
4
5
6
7
8
9
<script>
        if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
            $('.txtStoreLocatorZip_CssClass').click(function () {
                if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
                    $('.txtStoreLocatorZip_CssClass').val('');
                }
            });
        }
</script>

But, this won’t quite work because my textbox is in a UpdatePanel’s ContentTemplate and the javascript is not read on postback.

So, This is what I ended up doing (a simplified version):

1
2
3
4
5
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
	<ContentTemplate>
		<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
	</ContentTemplate>
</asp:UpdatePanel>
1
2
3
4
5
6
7
8
9
10
11
12
<script>
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
	function endRequestHandler(sender, args) {
		if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
			$('.txtStoreLocatorZip_CssClass').click(function () {
				if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
					$('.txtStoreLocatorZip_CssClass').val('');
				}
			});
		}
	}
</script>

This will add an endRequest handler to the end of the partial page postback so that you can call a nice little function at the end of it.

Hope this helps some people!