BumbleB2na
BumbleB2na

Reputation: 10763

Can browser autofill be prevented when input value changed programatically?

Turn on autofill in Chrome or Firefox. Using autofill in a form will change an input value unless it has been changed by a user.

Is it possible to prevent autofill from replacing input value if the value has been programmatically changed?

For added context to that question: Is there any attribute or event that can be triggered while programmatically changing input value? Would prefer to not have to change autocomplete or readonly attribute on the input field unless that's the only way to accomplish it.

<h1>Browser autofill</h1>
<p>
  <label for="name">Name</label>
  <input name="name" type="text" />
</p>
<p>
  <label for="street">Street</label>
  <input name="street" type="text" />
</p>
<p>
  <label for="province">Province</label>
  <input name="province" type="text" />
</p>
<p>
  <label for="country">Country</label>
  <input id="country" name="country" type="text" />
</p>
<div class="card">
  <button
    onClick="{ document.getElementById('country').value = 'Australia'; }"
    type="button"
  >
    Programmatically change Country
  </button>
</div>

Upvotes: 2

Views: 45

Answers (1)

Yaniek
Yaniek

Reputation: 82

You can prevent a browser from autofill after the input value was programmatically changed by setting an attribute "autocomplete" to "off" on the input element like this:

HTML:

<button
    onClick="changeAttribute()"
    type="button">Programmatically change Country
</button>

Javascript:

function changeAttribute() {
 document.getElementById("country").value = "Australia";document.getElementById("country").setAttribute("autocomplete", "off");
}

Explanation of the code: When the button is clicked it changes the value of the #country input to "Australia" and then it sets the attribute autocomplete to off on it. This attribute makes the browser unable to autofill the input.

Upvotes: 0

Related Questions