How to Get Input Value Using jQuery

This guide explains how to retrieve the value of an input field using jQuery. In web development, capturing user input from forms is a fundamental task, and jQuery simplifies this process with a dedicated built-in method. Below, you will learn the exact method to use, its syntax, and how to apply it to various HTML form elements such as text fields, select dropdowns, and checkboxes.

The .val() Method

The primary jQuery method used to retrieve the value of an input field is .val(). When called on a jQuery selector matching a form element, it returns the current value of the element's value attribute.

Basic Syntax

var inputValue = $('#elementId').val();

Practical Examples

1. Standard Text Input

To get the value from a standard text field:

HTML:

<input type="text" id="username" value="JohnDoe">

jQuery:

var username = $('#username').val();
console.log(username); // Outputs: JohnDoe

2. Dropdown Menus (<select>)

The .val() method automatically retrieves the value of the currently selected <option>:

HTML:

<select id="country">
  <option value="us">United States</option>
  <option value="ca" selected>Canada</option>
</select>

jQuery:

var selectedCountry = $('#country').val();
console.log(selectedCountry); // Outputs: ca

3. Radio Buttons

To get the value of the checked radio button within a specific group, combine the element selector with the :checked pseudo-class:

HTML:

<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female" checked> Female

jQuery:

var selectedGender = $('input[name="gender"]:checked').val();
console.log(selectedGender); // Outputs: female

4. Handling Real-Time User Input

You can retrieve the value dynamically as the user types by pairing .val() with an event listener like .on('input') or .on('change'):

$('#username').on('input', function() {
    var currentText = $(this).val();
    console.log(currentText);
});

Summary

Use the jQuery .val() method whenever you need to read the contents of form controls, including <input>, <select>, and <textarea>. Calling .val() with no arguments retrieves the value, while passing a string as an argument—such as $('#username').val('New Name')—will set the field's value.