Get and set an ASP.NET TextBox value with jQuery
With jQuery, reading and writing a text box comes down to one method, .val(). Called without an argument it returns the current text; called with a string it replaces it. On an ASP.NET Web Forms page the work is in choosing a selector that matches the id ASP.NET actually renders.
Load jQuery
Web Forms does not include jQuery by default. Reference a copy you host yourself or a CDN build near the end of the page, before your own script:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
The hash above is the one published for jQuery 3.7.1 on the jQuery CDN. If you change the version, copy the matching integrity value from releases.jquery.com; a wrong hash makes the browser refuse the file.
Selecting the TextBox
An <asp:TextBox ID="txtEmail" runat="server" /> placed in a content page renders with an id such as MainContent_txtEmail (ClientIDMode Predictable) or ctl00_MainContent_txtEmail (AutoID). Four selectors work regardless:
<script>
// 1. The exact rendered id, written by the server
var $email = $("#<%= txtEmail.ClientID %>");
// 2. A class that ASP.NET never rewrites
// <asp:TextBox ID="txtEmail" runat="server" CssClass="js-email" />
var $email2 = $(".js-email");
// 3. A static id: <asp:TextBox ID="txtEmail" runat="server" ClientIDMode="Static" />
var $email3 = $("#txtEmail");
// 4. An "ends with" attribute selector (slower, and can match several controls)
var $email4 = $("input[id$='_txtEmail'], #txtEmail");
</script>
Prefer the first three. The attribute suffix selector is handy when you cannot edit the markup, but a second control called, for example, txtEmailConfirm will not match while one called oldtxtEmail inside another container could.
Reading and writing
var current = $email.val(); // read
$email.val("someone@example.org"); // write
$email.val(""); // clear
// Transform the existing text with a callback
$email.val(function (index, value) {
return value.trim().toLowerCase();
});
.val() on a set of several elements returns the value of the first one, but setting a value applies it to all of them. Use .each() when you need per-element logic.
Do not use .attr("value") to read what the user typed: it returns the attribute as rendered by the server. .val() reads the live property.
Reacting while the user types
The input event fires on every change, including paste and drag-and-drop; change fires when the box loses focus with a different value. A live character counter for a multiline box:
<asp:TextBox ID="txtComment" runat="server" TextMode="MultiLine" Rows="4" MaxLength="280" />
<span id="counter">0 / 280</span>
<script>
$(function () {
var $box = $("#<%= txtComment.ClientID %>");
$box.on("input", function () {
$("#counter").text($box.val().length + " / 280");
}).trigger("input");
});
</script>
Check the rendered HTML: depending on the framework version, MaxLength may not be written on a multiline box. If it is missing, add it with txtComment.Attributes["maxlength"] = "280";. Either way the limit only guides the browser, so the server must check the length again.
Copying values between boxes
A typical form copies a billing address to a shipping address when a check box is ticked:
<asp:TextBox ID="txtBilling" runat="server" />
<asp:CheckBox ID="chkSame" runat="server" Text="Ship to the same address" />
<asp:TextBox ID="txtShipping" runat="server" />
<script>
$(function () {
var $billing = $("#<%= txtBilling.ClientID %>");
var $shipping = $("#<%= txtShipping.ClientID %>");
$("#<%= chkSame.ClientID %>").on("change", function () {
if (this.checked) {
$shipping.val($billing.val()).prop("readonly", true);
} else {
$shipping.prop("readonly", false);
}
});
$billing.on("input", function () {
if ($("#<%= chkSame.ClientID %>").is(":checked")) {
$shipping.val($billing.val());
}
});
});
</script>
The shipping box is made read-only with the HTML property rather than disabled. A disabled field is left out of the form submission, so the server would never receive the copied address.
Text boxes inside a GridView
In a TemplateField, each row gets its own id (gvItems_txtQty_0, gvItems_txtQty_1…), so ClientID cannot be written once in the page. Give the boxes a class and work relative to the row:
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="false" CssClass="items">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Item" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<span class="price" data-price='<%# Eval("Price") %>'><%# Eval("Price", "{0:0.00}") %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server" CssClass="qty" Text="1" Columns="3" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate><span class="total"></span></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script>
$(function () {
$(".items").on("input", "input.qty", function () {
var $row = $(this).closest("tr");
var price = parseFloat($row.find(".price").data("price"));
var qty = parseInt($(this).val(), 10) || 0;
$row.find(".total").text((price * qty).toFixed(2));
});
$(".items input.qty").trigger("input");
});
</script>
data-price is rendered by Eval("Price") using the server's current culture. On a server with a French or German culture the decimal separator is a comma and parseFloat stops at it. Format it invariantly, for example <%# ((decimal)Eval("Price")).ToString(System.Globalization.CultureInfo.InvariantCulture) %>, when the value is meant for script.
Totals computed in the browser are a convenience for the user only. Recalculate them on the server from the posted quantities and the prices in your database.
Reading the value on the server
protected void btnOrder_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvItems.Rows)
{
var box = (TextBox)row.FindControl("txtQty");
if (!int.TryParse(box.Text, out int qty) || qty < 0 || qty > 999)
{
// reject or correct the value
continue;
}
// use qty
}
}
Remember to bind the grid inside if (!IsPostBack) in Page_Load. Rebinding on every request recreates the rows before the button event runs and discards what the user typed.
Checklist
- Use
.val()to read and write;.prop("readonly")or.prop("disabled")for state. - Build selectors from
ClientID, a CSS class orClientIDMode="Static". - Put the code inside
$(function () { … })or at the end of the body. - Re-validate everything on the server.
For the plain JavaScript version, including the read-only and disabled rules in more detail, see Get and set a TextBox value with JavaScript.
Official documentation
- jQuery API: .val(), .prop(), .on(), Attribute Ends With selector
- Microsoft Learn: TextBox class, ClientIDMode
- MDN: input event