Menü schliessen
Created: November 15th 2018
Categories: IT Development,  Web Browsers,  Wordpress
Author: Marcus Fleuti

The solution for a bug where autocomplete="off" doesn't apply

Tags:  Autocomplete,  Autofill,  Bug,  CSS,  HTML,  input,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Sometimes, a strange bugs can appear in the browser's behavior. Even more stranger - those bugs can persist and stay there for a while without any logical explanation. On of those is a bug where HTML Attribute autocomplete is completely ignored by the browsers. Or partly ignored, just to make more confusion. There is a lot of solutions on Internet, where instead of writing autocomplete="off" should be autocomplete="X" (where X is random string of characters). And it works. Not every time. Not every day. In not all browsers and not in all versions of the same browser. So how to solve this problem, because in some projects we really need this to be removed?

So, do we have any solution for this autocomplete problem?

Solution is quite simple - use textarea insead of input! This would prevent autofill option in browsers since textarea doesn't have that option implemented at all. But the next problem we are facing here is we need to make textarea to behave exactly like input field. That means: remove resizing, give it some height, force text to continue in one line and not to break in multiple lines, remove scrollbars if there is a lot of text. So, HTML will be something like this:
<textarea id="input-text" placeholder="Textarea like text input"></textarea>
CSS will be:

textarea {
  height: 18px;
  resize: none;
  white-space: pre;
  overflow-wrap: normal;
  overflow: hidden;
  padding: 5px;
}

Now, we have solved those mentioned problems, but textarea by default has spellcheck included. To turn it off, add additional attribute spellcheck="false" in textarea, and now HTML looks like this:
<textarea id="input-text" placeholder="Textarea like text input" spellcheck="false"></textarea>
By pressing enter button on keyboard textarea's default behavior is to go to the new line. By doing the same while focus is on input field we usually submit the form. so, let's do this with jQuery:

$('#input-text').bind('keypress', function(e) {
  if ((e.keyCode || e.which) == 13) {
    e.preventDefault();
    alert('Success!');
    // you can here submit the form i.e.
  }
});

 
And that's it, we have now a textarea which behaves like text input! Working example can be found here: https://jsfiddle.net/4sm7zypb/.