Question

How to Get Input Text Box Values with jQuery

htmljqueryjquery-selectorstextinputhtml-input

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 released
  • input — runs when the value changes
  • change — runs when the input loses focus after being changed
  • click — 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:

  1. Select the input
  2. Listen for an event
  3. Get the current value with .val()
  4. 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 keyup or input
  • 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.”

Take Quiz

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:

  1. The page loads.
  2. $(document).ready(...) waits until the DOM is ready.
  3. jQuery finds the element with id txt_name.
  4. An input event handler is attached to that element.
  5. The user types A into the box.
  6. The input event fires.
  7. Inside the handler, $(this) refers to the input element that triggered the event.
  8. .val() reads the current value, which is now A.
  9. $("#output").text(currentValue) puts A into the paragraph.
  10. 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 becomes J
  • Jo → output becomes Jo
  • John → output becomes John

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.

Take Quiz

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

  • input updates as the value changes
  • change usually 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

ApproachWhen it runsBest forNotes
keyupAfter a key is releasedSimple typing reactionsDoes not cover every kind of input change
inputWhenever the value changesLive updatesUsually the best choice for text inputs
changeWhen value changes and field loses focusForms and final value checksNot ideal for live preview
click on a buttonOnly after button pressSubmit-like actionsGood when user explicitly confirms

.val() vs .text() vs .html()

MethodUsed forWorks for input values?Example
.val()Form element valuesYes$("#name").val()
.text()Plain text contentNo, not for reading typed input$("#output").text("Hello")
.html()HTML content inside an elementNo, not for reading typed input$("#box").html("<b>Hello</b>")

Native JavaScript vs jQuery

TaskjQueryNative 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.

Take Quiz

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 input for live updates
  • Use change when 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
  • keyup does not catch every possible value change
  • alert() 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");
Take Quiz

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

  1. Add a text input for the user's name.
  2. Add an element to display the live output.
  3. Use jQuery to listen for changes in the input.
  4. Read the value with .val().
  5. Render the value with .text().
  6. Show a fallback message when the input is empty.
Take Quiz

Keep learning

Related questions

View more