How to Set Default HTML Form Focus Without JavaScript?

A HTML form is a section of a document that includes controls like text fields, password fields, checkboxes, radio buttons, a submit button, menus, and so on. It allows the user to enter any data like name, email address, password, phone number, and so on that will be sent to the server for processing.

HTML forms are required if we want to collect information from site visitors. The syntax for creating a form is given below.


--form elements?

Example

Here is an example showing a simple form with its default behavior.



    Example of a form without any focused element


    

Restaurant Experience





What did you like the most?








As we can observe, the above form does not have any focus element. A focus element is the one that receives all the keyboard events and other similar events by default. Basically, when focus is set to a particular element in a form, it appears to be highlighted among the other elements. When this page is loaded, this control receives focus and displays a blinking text cursor.

Generally, the focus() method of JavaScript is used for this purpose as it makes the element the current document's active element. However, we can also achieve this without using JavaScript. The method to set default HTML form focus is discussed below.

Using the ?autofocus? Attribute

The HTML autofocus attribute is a boolean attribute that specifies whether an element should be given focus when the page loads. HTML5 introduced the autofocus attribute. The autofocus attribute is applicable to the following elements:

  • This tag defines a button that is clickable.

  • This tag generates a multi-line input element.

  • : This tag generates a multi-line input element.

  • This tag generates a dropdown control.

Syntax

 

The autofocus attribute may be applied only to one element in the document or dialogue. When applied to multiple elements, only the first one will be highlighted.

Example

This is a simple example that demonstrates the use of autofocus attribute on a single input element inside a form.


  
    How to Set Default HTML Form Focus Without JavaScript?
    
  
  
     

Example

In this example, we will create a form with multiple input elements and add the autofocus attribute to a single element to highlight that particular element.


  
    How to Set Default HTML Form Focus Without JavaScript?
    
    
      

Airline review




Choose the airline




In the above example, we have added the autofocus attribute to the first input element and as a result only that element gets highlighted in the form. Similarly, we can choose to add the autofocus attribute on any element to set the focus on it when the page loads.

Updated on: 2023-09-12T10:30:39+05:30

870 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements