How to Set Textbox Value Using jQuery
Setting the value of a text box dynamically is a fundamental task in
web development, often required for form pre-filling, data resets, or
responding to user interactions. In jQuery, this process is accomplished
cleanly and efficiently using the built-in .val() method.
This guide explains how to use .val() with various jQuery
selectors, how to clear an input field, and how to properly trigger
related events after updating a text box.
The jQuery .val()
Method
The primary tool for setting or getting input values in jQuery is the
.val() function. When passed a string or number as an
argument, it replaces the current content of the targeted text box.
$("#myInput").val("Hello, World!");Setting Values Using Different Selectors
You can target text boxes using standard CSS selectors within jQuery:
By ID:
// Targets an input with id="username"
$("#username").val("JaneDoe");By Class: Targeting by class sets the value for all matching text boxes simultaneously.
// Sets the value for every input with class="auto-fill"
$(".auto-fill").val("Default Value");By Attribute: Targeting by the name
attribute or type is useful when IDs are not available.
// Targets an input with name="user_email"
$('input[name="user_email"]').val("user@example.com");Clearing a Text Box
To empty a text box, pass an empty string "" to the
.val() method:
$("#myInput").val("");Modifying Value Based on Current Content
You can also pass a callback function to .val(). The
function receives the element's index and its current value, allowing
you to compute a new value dynamically:
$("#counterInput").val(function(index, currentValue) {
return parseInt(currentValue || 0, 10) + 1;
});Triggering Change Events
Programmatically updating an input field with .val()
does not trigger native browser events like change or
input. If your application relies on event listeners
attached to the text box, chain the .trigger() method to
notify those listeners:
$("#myInput").val("Updated Data").trigger("change");