How to disable the autofill in browser text inputs selectively via code?

Look at the autocomplete HTML attribute (on form or input tags).

<form [...] autocomplete="off"> [...] </form>

W3C > Autocomplete attribute

Edit:

Nowadays - from the comments - web browsers do not always respect the autocomplete tag defined behavior. This non-respect could be surrounded with a little of JavaScript code but you should think about you want to do before use this.

First, fields will be filled during the page loading and will only be emptied once the page load. Users will question why the field has been emptied.

Second, this will reset other web browser mechanisms, like the autofill of a field when you go back to the previous page.

jQuery( function()
{
  $("input[autocomplete=off]").val( "" );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post" action="">
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" id="username" name="username" value="John" autocomplete="off">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" id="password" name="password" value="qwerty" autocomplete="off">
  </div>
  <input type="submit" value="Login">
</form>

you can put it into your inputs:

<input type="text" name="off" autocomplete="off">

or in jquery

$(":input").attr("autocomplete","off"); 

There are 2 solutions for this problem. I have tested following code on Google Chrome v36. Recent Version of Google Chrome forces Autofill irrespective of the Autocomplete=off.Some of the previous hacks don't work anymore (34+ versions)

Solution 1:

Put following code under under <form ..> tag.

<form id="form1" runat="server" >
<input style="display:none" type="text" name="fakeusernameremembered"/>
<input style="display:none" type="password" name="fakepasswordremembered"/>

...

Read more

Solution 2:

$('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {

                var input = this;
                var name = $(input).attr('name');
                var id = $(input).attr('id');

                $(input).removeAttr('name');
                $(input).removeAttr('id');

                setTimeout(function () {
                    $(input).attr('name', name);
                    $(input).attr('id', id);
                }, 1);
            });

It removes "name" and "id" attributes from elements and assigns them back after 1ms.


Adding an autocomplete=off attribute to the html input element should do that.