With this jQuery code, I am attempting to select the text inside the control, when clicked.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(
function () {
jQuery("input[type='text']").click(function () {
this.select();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox Text="Text 1" ID="txt1" ClientIDMode="Static" runat="server" />
<asp:Button Text="Submit" ID="btn1" OnClick="btn1_Click" runat="server" />
<asp:TextBox Text="Text 2" ID="txt2" ClientIDMode="Static" Visible="false" runat="server" />
</div>
</form>
</body>
</html>
Code Behind:
protected void btn1_Click(object sender, EventArgs e)
{
txt2.Visible = true;
}
The issue is when I put contents of the page inside UpdatePanel, jQuery works on first time on txt1. On button click it doesn’t work for any of the textboxes.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TextBox Text="Text 1" ID="txt1" ClientIDMode="Static" runat="server" />
<asp:Button Text="Submit" ID="btn1" OnClick="btn1_Click" runat="server" />
<asp:TextBox Text="Text 2" ID="txt2" ClientIDMode="Static" Visible="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
While debugging using Chrome console I found jQuery is not defined – strange 🙁 Can you please suggest what could be issue.
Thank you for your time.
EDIT: Based on your responses I tried following these solutions, both worked fine for me.
Binding on event to the form1, and include this on document ready.
> jQuery(document).ready( > function () { > jQuery("#form1").on("click", "input[type='text']", function () { > this.select(); > }); > });
Binding on event to the document itself –
jQuery(document).on(“click”, “input[type=’text’]” ,function () {
this.select();
});
First one seem to be more safe to me with higher performance, what do you suggest ?
When the content in the update panel is update, the elements are replaced with new elements that doesn’t have the event bindings.
You need to use delegate instead of binding the event on the element itself. Bind it on the element surrounding the update panel, so it can handle the event after the content in the update panel has been replaced:
For jQuery 1.4.2 and later:
For jQuery 1.7 and later: