Select event in jQuery


In this lesson, you will learn about the jQuery select event, which is fired by the web browser when a user selects, completes or partial types in a text field or text area.

Introduction to Select event in jQuery

This event is limited to form elements: <input type="text"> and <textarea> boxes. When the select event is fired, you can bind a function to execute a piece of code each time the select event occurs.

The syntax of jQuery is:

.select(function(){});

The argument here is optional. You can also write .select() without any parameter.

This is a short form of .on("select", function(){}).

Example of Select event in jQuery

In this example, we will create a simple text field, which has value by default. When a user selects the text from the text field, the web browser will print a display message.

Example of Select event in jQuery
Select event is fired

The HTML

<div id="container">
   <form action="">
      <input type="text" name="txt" id="txt" value="Tutorialspanel.com - Your source of programming Tutorials.">
      <br>
      <p id="msg"> </p>
   </form>
</div>

The CSS

label {
	width: 300px;
	display: block;
}

input {
	width: 80%;
	padding: 5px;
}

The jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" ></script> 
<script >
    $(document).ready(function() {
        $("#txt").select(function() {
            $("#msg").text("Did you just select text above?").show();
        });
    }); 
</script>

This event hasn’t been used much in the web development, but you can use in apps where the text is important, like a grammar verification app or the situations where you don’t want the user to copy the text. You can create an alert message, whenever the user tries to copy the text by selecting it.

jQuery Change Event Tutorial Home jQuery Keyboard Events

 

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply