Open In App

How to set cursor in search form by clicking on button in jQuery ?

Given a search form, we need to set the cursor in the search form on clicking a button using jQuery. This can be done by using the focus() method and click() method.

We will create a web page with a textbox and a button. We will add the functionality using jQuery such that on clicking the button, the cursor is set to the textbox. Now let us discuss some methods that we will use in the implementation.



click() Method: The click() method in jQuery starts the click event or runs the function passed to it when a click event is triggered.

Syntax:



$(selector).click(function);

Parameter: It accepts an optional parameter “function”, which will run when a click event occurs.

Return Value: It returns the selected element with the specified function to perform.

focus() Method: The focus() method triggers the focus event or runs the function passed to it when a focus event is triggered. The focus() method can be used to focus a specific element by using the selector.

Syntax:

$(selector).focus()

Parameter: It accepts an optional parameter “function”  which will run when a focus event occurs.

jQuery CDN Links:

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>

Steps:

Example:




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href=
    <script src=
    </script>
 
    <style>
        body {
            margin-left: 10px;
            margin-right: 10px;
        }
    </style>
</head>
 
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <strong>Set cursor in search form</strong>
    <br />
    <form class="form-inline mt-4">
        <input type="text" class="form-control mx-2"
            id="textInput" placeholder="Focus Me...">
             
        <button id="focusButton" type="button"
            class="btn btn-secondary">
            Click Here To Focus
        </button>
    </form>
 
    <script>
        $(document).ready(function () {
            $('#focusButton').click(function () {
                $("#textInput").focus();
            })
        });
    </script>
</body>
 
</html>

Output:


Article Tags :