Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu May 23, 2023 › #HowTo #Javascript

How to set focus on textbox on button click in JavaScript

Hey there, Today, I'm going to explain how to set focus on an input text box using the focus() method. It's a way to make a text box active so that you can start typing in it right away. Let's get started!

Step 1: Adding a Button and a Text Box:#

The first thing we need to do is create a button and a textbox on our webpage. The button will help us activate the text box when we click on it.
<button onclick="setFocus()">Set focus</button>
<input type="text" id="my-text-box">

Step 2: Creating a JavaScript Function:#

Now, let's write the JavaScript code that will set the focus on the textbox when the button is clicked. We'll call the setFocus() method.

In the setFocus() function, we first use the document.getElementById() method to get the reference to our text box. We pass the ID of the text box, which is my-text-box, as a parameter to this method. This allows us to access the text box from our JavaScript code.

Next, we use the focus() method on the text box object. This method sets the focus on the text box, making it active and ready for input.

So, when we call textBox.focus(), the cursor will automatically appear in the text box, and you can start typing without having to click on it manually.

Conclusion:#

And there you have it, By adding a button and using a simple JavaScript function, we can set focus on an input text box, making it active and ready for typing.

save
listen
AI Answer
Write Your Answer
loading
back
View All