HTML DOM Form autocomplete Property


The HTML DOM Form autocomplete property is associated with the autocomplete attribute of the form element. Using the autocomplete property we can set or return autocomplete attribute value of the given form. This property specifies if the input field should autocomplete text being written by the user based on the text that was previously written in the text field.

The autocomplete property can be turned off for specific input fields if autocomplete is set on for the form and it is true for vice-versa also.

Syntax

Following is the syntax for −

Set the autocomplete property −

formObject.autocomplete = on|off

Here, “on” is by default and the browser tries to autocomplete the user values based on previous text. Setting it to off means the browser will not complete the user input and the user have to type the values himself.

Example

Let us look at an example of the autocomplete property −

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   form{
      border:2px solid blue;
      margin:2px;
      padding:4px;
   }
</style>
<script>
   function changeAuto() {
      document.getElementById("FORM1").autocomplete = "on";
      document.getElementById("Sample").innerHTML = "The input text will now be autocomplete
";
   }
</script>
</head>
<body>
<h1>Form autocomplete property example</h1>
<form id="FORM1" autocomplete="off">
<label>User Name <input type="text" name="usrN"></label> <br><br>
<label>Password <input type="password" name="pass"></label>
</form>
<br>
<button onclick="changeAuto()">CHANGE</button>
<p id="Sample"></p>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button and typing text in the User Name field −

In the above example −

We have created a form with id=“Form1” and autocomplete set to “off”. This means that the user will have to type the values himself with no help from the web browser to autocomplete this text. The form contains a text field and a password field too −

<form id="FORM1" autocomplete="off">
<label>User Name <input type="text" name="usrN"></label> <br><br>
<label>Password <input type="password" name="pass"></label>
</form>

We then created a button CHANGE that will execute the changeAuto() method when clicked by the user −

<button onclick="changeAuto()">CHANGE</button>

The changeAuto() method gets the form element using the getElementById() method and sets it autocomplete property to “on” from “off”. Using the innerHTML property of a paragraph with id “Sample” we show this change by displaying text to the user −

function changeAuto() {
   document.getElementById("FORM1").autocomplete = "on";
   document.getElementById("Sample").innerHTML = "The input text will now be autocomplete ";
}

Updated on: 19-Feb-2021

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements