Select Input Elements of Type Text in jQuery
This guide explains how to target and select text input fields using jQuery selectors. You will learn the primary syntax methods—including standard CSS attribute selectors and jQuery-specific pseudo-selectors—along with practical examples for manipulating values, handling events, and understanding performance differences between the approaches.
Standard Attribute Selector (Recommended)
The most efficient and recommended way to select text input elements is by using the standard CSS attribute selector:
$('input[type="text"]')This syntax relies on the browser's native
querySelectorAll implementation, making it significantly
faster than custom pseudo-selectors.
jQuery Pseudo-Selector
jQuery also provides a shorthand pseudo-selector specifically for text inputs:
$(':text')While convenient, :text is deprecated as of jQuery 3.4.0
because it does not use native browser queries and can introduce minor
performance overhead. It also matches plain <input>
tags that do not have an explicit type attribute defined,
since text is the default HTML input type.
Common Usage Examples
Once selected, you can chain standard jQuery methods to read or modify the elements.
Reading and setting values:
// Get the value of the first text input
let currentValue = $('input[type="text"]').val();
// Set a new value for all text inputs
$('input[type="text"]').val('Default Text');Applying styles or classes:
// Add a CSS class to all text inputs
$('input[type="text"]').addClass('highlighted-border');
// Disable all text inputs
$('input[type="text"]').prop('disabled', true);Attaching event listeners:
// Trigger an alert on focus
$('input[type="text"]').on('focus', function() {
$(this).css('background-color', '#f0f8ff');
});Best Practice
Always prefer $('input[type="text"]') over
$(':text'). To maximize performance on complex pages, scope
the selector to a parent container, such as
$('#form-id input[type="text"]'), to limit the scope of the
DOM traversal.