jQuery Event select() Method



The jQuery event select() method binds an event handler to the select event or triggers that event when the text within the <input> or <textarea> element is selected.

Syntax

Following is the syntax of the jQuery event select() method −

$(selector).select(function)

Parameters

This method accepts a parameter as a function, which is described below −

  • function (optional) − An optional function to execute when the select event occurs.

Return Value

This method does not have any return value.

Example 1

The following is the basic example of the jQuery event select() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Select the text within the below input field.</p>
    Company Name: <input type="text" value="TutorialsPoint">
    <script>
        $('input').select(function(){
            alert("You select text within the input field.")
        });
    </script>
</body>
</html> 

Output

The program above program displays an input field with a predefined value. When the user selects text within this input field, a pop-up alert message will appear on the browser screen −


Example 2

Here's another example of the jQuery event select() method. We use this method to display the text whenever the text within the text area is selected −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Select the text within the below textarea field.</p>
    Write your valuable Feedback: <br><textarea name="" id="" cols="30" rows="10"></textarea>
    <span></span>
    <script>
        $('textarea').select(function(){
            $('span').text($('textarea').val());
        });
    </script>
</body>
</html>

Output

After executing the above program, a textarea field will displayed. If you write and then select text within this textarea, the selected text will be shown next to the textarea field −


Example 3

Change the background color of an input field when text inside the input field is selected −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Select the text within the below input field to change the background color.</p>
    Name: <br><input type="text">
    <span></span>
    <script>
        $('input').select(function(){
            $(this).css({"background-color": "green", "color": "white"});
        });
    </script>
</body>
</html>

Output

Once the above program is executed, it will display an input field. When text within the input is selected, the background changes to green −


jquery_ref_events.htm
Advertisements