How to select all on focus in input using jQuery?

In this tutorial, we are going to discuss how to select all the text in an input field on focus using jQuery?
Submitted by Pratishtha Saxena, on August 11, 2022

Answer: To select all on focus in input - we can use jQuery .focus() event.

jQuery focus() Event

The focus() is an event in jQuery. As soon as the user focuses on an input box, this event gets triggered. A function can be attached to it and as soon as the event is fired, this function gets executed.

Syntax:

$(selector).focus();
$(selector).focus(function(){});

The function over here is optional, it can be or cannot be attached to it. Using this function, any task can be performed on the focussed field. For example, the CSS of the input field can be changed or highlighted, etc.

Yes, we can also select the complete text present in the input field with one click with the help of this focus() event. For this, the select() method is used inside the function to be executed. This method helps in selecting the text for a particular selector.

Let's implement both, focus() and select() in an example.

Code to to select all on focus in input using jQuery

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <h1>FORM</h1>
	
    <form id="myForm">
      <label>Name:</label>
      <input type="text" id="name"><br><br>
	  
      <label>Email Id:</label>
      <input type="email" id="email"><br><br>
	  
      <label>Country:</label>
      <select id="country">
        <option value="India">India</option>
        <option value="USA">USA</option>
        <option value="England">England</option>
        <option value="Australia">Australia</option>
        <option value="Germany">Germany</option>
      </select>
	  
      <br><br>
	  
      <button type="submit">Submit</button>
	  
    </form>
	
  </body>
</html>

jQuery:

$(document).ready(function() {
    $('#name,#email,#country').focus(function() {
        $(this).select();
        $(this).css('background-color', 'yellow')
    });
});

Output:

Example: Select all on focus in input





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.