Question
How can I get the current value of a text input and display or use that value with jQuery?
For example, one approach is to read the value during a keyboard event:
$(document).ready(function() {
$("#txt_name").keyup(function() {
alert($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<input type="text" id="txt_name" />
What are the common ways to get an input value and render it on the page using jQuery?
Short Answer
By the end of this page, you will understand how to read the value of a text input in jQuery, when to use .val(), which events commonly trigger value reading, and how to display that value in the page instead of only showing it in an alert.
Concept
In jQuery, the most common way to get the value of an <input> element is with the .val() method.
$("#txt_name").val()
This reads the current value typed into the input field.
To make this useful, you usually combine .val() with an event such as:
keyup— runs after a key is releasedinput— runs when the value changeschange— runs when the input loses focus after being changedclick— useful when reading a value after pressing a button
Why this matters:
- Forms need to collect user input
- Search boxes need to react to what users type
- Validation needs to check whether a value is empty or valid
- Interfaces often display live previews of text being entered
jQuery makes this easier by giving you a simple way to select elements and work with their values.
A common pattern is:
- Select the input
- Listen for an event
- Get the current value with
.val() - Render or process that value
For example:
$("#txt_name").on("input", function() {
const value = $(this).val();
$("#output").text(value);
});
This is more practical than using alert(), because alerts interrupt the user experience while on-page rendering updates smoothly.
Mental Model
Think of an input box as a small container that holds text.
- The user types text into the container
.val()opens the container and reads what is inside- An event tells your code when to check the container
- Rendering means taking that value and showing it somewhere else
A simple analogy:
- The input is a note box
- The user drops in a note
- jQuery waits for a signal like
keyuporinput - Your code reads the note and copies it onto a display board
So the full idea is not just “get the value,” but also “get the value at the right time.”
Syntax and Examples
The core syntax for reading an input value is:
$("selector").val()
To set a value, use:
$("selector").val("new value")
Example 1: Read value on button click
<input type="text" id="txt_name" />
<button id="showBtn">Show Value</button>
<p id="output"></p>
<script>
$(document).ready(function() {
$("#showBtn").click(function() {
const name = $("#txt_name").val();
$("#output").text(name);
});
});
</script>
What this does
- Waits for the button click
- Reads the current input value using
.val() - Displays the value inside the paragraph using
.text()
Example 2: Show value as the user types
<input type="text" id="txt_name" />
<p id="output"></p>
<script>
$(document).ready(function() {
$("#txt_name").on("input", function() {
const name = $(this).val();
$("#output").text(name);
});
});
</script>
Why input is often better than keyup
- It reacts to more kinds of value changes
- It works for typing, pasting, and some autofill cases
- It is usually better for live updates
Example 3: Get value when the field changes
<input type="text" id="txt_name" />
<p id="output"></p>
<script>
$(document).ready(function() {
$("#txt_name").change(function() {
$("#output").text($(this).val());
});
});
</script>
This runs when the user changes the value and then leaves the field.
Step by Step Execution
Consider this example:
<input type="text" id="txt_name" />
<p id="output"></p>
<script>
$(document).ready(function() {
$("#txt_name").on("input", function() {
const currentValue = $(this).val();
$("#output").text(currentValue);
});
});
</script>
Here is what happens step by step:
- The page loads.
$(document).ready(...)waits until the DOM is ready.- jQuery finds the element with id
txt_name. - An
inputevent handler is attached to that element. - The user types
Ainto the box. - The
inputevent fires. - Inside the handler,
$(this)refers to the input element that triggered the event. .val()reads the current value, which is nowA.$("#output").text(currentValue)putsAinto the paragraph.- If the user continues typing
Alex, the same steps repeat, and the paragraph updates each time.
Trace example
If the user types these characters:
J→ output becomesJJo→ output becomesJoJohn→ output becomesJohn
This is a simple example of reactive UI behavior: the page updates when the user input changes.
Real World Use Cases
Getting input values is used everywhere in web development.
Common examples
- Search boxes: read what the user types and filter results
- Login forms: collect email and password values
- Live previews: show a username, title, or message as it is typed
- Validation: check whether a field is empty before submitting
- Calculators: read numeric values and compute results
- Filters: update product or table views based on typed text
Example: simple live search text
$("#search").on("input", function() {
const keyword = $(this).val().toLowerCase();
$("#searchStatus").text("Searching for: " + keyword);
});
Example: form validation
$("#nameForm").submit(function(event) {
const name = $("#txt_name").val().trim();
if (name === "") {
event.preventDefault();
$("#error").text("Name is required.");
}
});
In real apps, reading input values is often the first step before validation, formatting, or sending data to a server.
Real Codebase Usage
In real projects, developers rarely use alert() for input values. They usually combine .val() with structured patterns.
1. Validation before processing
const email = $("#email").val().trim();
if (email === "") {
$("#error").text("Email is required.");
return;
}
This is a guard clause: stop early if the value is invalid.
2. Read once, reuse many times
$("#saveBtn").click(function() {
const name = $("#txt_name").val().trim();
const city = $("#txt_city").val().trim();
$("#summary").text(name + " from " + city);
});
This avoids calling .val() repeatedly.
3. Live UI updates
$("#titleInput").on("input", function() {
$("#previewTitle").text($(this).val());
});
This is common for previews, editors, and dashboards.
4. Sanitizing or formatting input
$("#username").on("input", function() {
const cleanValue = $(this).val().trim();
$("#status").text(cleanValue);
});
5. Working with forms
$("form").submit(function(event) {
event.preventDefault();
const formData = {
name: $("#txt_name").val(),
age: $("#txt_age").val()
};
console.log(formData);
});
In larger codebases, developers often gather several input values together, validate them, and then pass them to another function or API request.
Common Mistakes
1. Using .text() instead of .val() for inputs
Broken code:
const name = $("#txt_name").text();
Why it is wrong:
.text()reads text content between tags<input>elements do not store user input as inner text
Correct code:
const name = $("#txt_name").val();
2. Forgetting to wait for the DOM
Broken code:
$("#txt_name").on("input", function() {
console.log($(this).val());
});
If this runs before the input exists, the handler may not attach.
Correct code:
$(document).ready(function() {
$("#txt_name").on("input", function() {
console.log($(this).val());
});
});
3. Using alert() for every key press
Broken pattern:
$("#txt_name").keyup(function() {
alert($(this).val());
});
Why it is a problem:
- Alerts interrupt typing
- The user experience becomes frustrating
Better approach:
$("#txt_name").on("input", function() {
$("#output").text($(this).val());
});
4. Not trimming user input when needed
const name = $("#txt_name").val();
This might contain spaces at the beginning or end.
Better:
const name = $("#txt_name").val().trim();
5. Confusing change and input
inputupdates as the value changeschangeusually runs after the field loses focus
Choose the event based on the behavior you want.
6. Assuming all input values are numbers
const total = $("#price").val() + 10;
If #price contains 5, the result may be 510 because the value is a string.
Correct approach:
const total = Number($("#price").val()) + 10;
Comparisons
Common ways to read input values
| Approach | When it runs | Best for | Notes |
|---|---|---|---|
keyup | After a key is released | Simple typing reactions | Does not cover every kind of input change |
input | Whenever the value changes | Live updates | Usually the best choice for text inputs |
change | When value changes and field loses focus | Forms and final value checks | Not ideal for live preview |
click on a button | Only after button press | Submit-like actions | Good when user explicitly confirms |
.val() vs .text() vs .html()
| Method | Used for | Works for input values? | Example |
|---|---|---|---|
.val() | Form element values | Yes | $("#name").val() |
.text() | Plain text content | No, not for reading typed input | $("#output").text("Hello") |
.html() | HTML content inside an element | No, not for reading typed input | $("#box").html("<b>Hello</b>") |
Native JavaScript vs jQuery
| Task | jQuery | Native JavaScript |
|---|---|---|
| Get input value | $("#txt_name").val() | document.getElementById("txt_name").value |
| Set text output | $("#output").text(name) | document.getElementById("output").textContent = name |
| Attach input event | $("#txt_name").on("input", handler) | element.addEventListener("input", handler) |
jQuery provides shorter syntax, while native JavaScript is more common in modern codebases.
Cheat Sheet
// Get input value
$("#txt_name").val();
// Set input value
$("#txt_name").val("Alice");
// Read value on input
$("#txt_name").on("input", function() {
const value = $(this).val();
});
// Read value on keyup
$("#txt_name").keyup(function() {
const value = $(this).val();
});
// Read value on change
$("#txt_name").change(function() {
const value = $(this).val();
});
// Render value into another element
$("#output").text($("#txt_name").val());
Quick rules
- Use
.val()for form values - Use
.text()to display plain text in another element - Prefer
inputfor live updates - Use
changewhen you only care about the final changed value - Use
.trim()if extra spaces should be removed - Input values are strings unless you convert them
Edge cases
- Empty input returns
"" - Numeric input still returns a string
keyupdoes not catch every possible value changealert()is not a good way to render live input
FAQ
How do I get the value of a text box in jQuery?
Use .val() on the selected input element:
const value = $("#txt_name").val();
How do I display an input value on the page with jQuery?
Read the input with .val() and write it to another element with .text():
$("#output").text($("#txt_name").val());
Which event should I use to detect typing in an input?
Use input in most cases. It is usually better than keyup because it responds to more types of changes.
Why is .text() not working on my input field?
Because .text() reads inner text content, and input fields store their user-entered value in .value, which jQuery accesses with .val().
Does .val() return a string or a number?
It returns a string. Convert it with Number() or parseInt() if you need a numeric value.
How do I get the value only after the user finishes editing?
Use the change event. It usually fires when the field loses focus after being modified.
Can I set an input value with jQuery too?
Yes:
$("#txt_name").val("New value");
Mini Project
Description
Build a small live name preview tool. The user types a name into a text box, and the page instantly shows the current value below it. This demonstrates how to read input values with jQuery and render them in real time.
Goal
Create a text input that updates a preview message as the user types.
Requirements
- Add a text input for the user's name.
- Add an element to display the live output.
- Use jQuery to listen for changes in the input.
- Read the value with
.val(). - Render the value with
.text(). - Show a fallback message when the input is empty.
Keep learning
Related questions
Add a Favicon to a Static HTML Page
Learn how to add a favicon to static HTML pages, use correct paths and icon formats, and troubleshoot browser caching and local-file issues.
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
Apply CSS !important with jQuery .css()
Learn why jQuery .css() cannot set !important and how to use CSSStyleDeclaration.setProperty() to apply inline important styles safely.