• jQuery Video Tutorials

jQuery :text Selector



The :text selector in jQuery is used to select all input elements of type "text" in the DOM.

Its primary use is for manipulating these specific elements, making it easier to perform tasks such as value setting, styling, and adding event listeners to text inputs in forms.

Syntax

Following is the syntax of jQuery :text selector −

$(":text")

Parameters

Following is the explantion of above syntax −

  • input: Specifies a selector that selects all text input elements in the entire document.

Example 1

In the following example, we are demonstrating the basic usage of jQuery :text selector −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                $(':text').val('New Value');
            });
        });
    </script>
</head>
<body>
    <form id="myForm">
        <input type="text" name="input1" placeholder="Enter text here"><br>
        <input type="text" name="input2" placeholder="Enter text here"><br>
        <button>Change Values</button>
    </form>
</body>
</html>

When we execute the program and click the button, the values of all text input fields will be changed to "New Value".

Example 2

In this example, we are changing the background color of all the text input elements −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                $(':text').css('background-color', 'yellow');
            });
        });
    </script>
</head>
<body>
    <form>
        <label for="input1">Username:</label>
        <input type="text" id="un"><br><br>
        <label for="input2">Password:</label>
        <input type="password" id="pwd"><br><br>
        <button>Change Values</button>
    </form>
</body>
</html>

After executing the program, the text input element's background color will be changed to yellow.

jquery_ref_selectors.htm
Advertisements