Remove auto complete on text box - html

I have a few text boxes on my page and find it very annoying the auto complete functionality. Is there any way to remove this from my site?

Auto Complete
As of HTML 5, the auto complete is a form / input Attribute suported by all major browsers.
<form name="form1" id="form1" method="post" autocomplete="off" action="#">
Also, see here some more information about its usage:
W3C cheatsheet
MDN
MSDN
Auto Capitalize and Auto Correct
If you are preparing an web application or any other Smartphone friendly web page, you might be interested in knowing how to: Disable Autocomplete, Autocapitalize, and Autocorrect.
<input autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
<textarea autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>

Add autocomplete="off" as form attribute and it applies to all fields inside the form.
Example : <form action="#" autocomplete="off">

This is how you can do this
autocomplete="new-text"
Add inside you input box or textarea

autocomplete="off" can be added as a non-standard attribute to input fields. not sure which browsers besides IE support it though.

autocomplete="off" do not support instead of that use this 'autocomplete="new-password"'

You can use jQuery to add the autocomplete attribute after the page loads. That's the best way I found to force Chrome to listen.
<script type="text/javascript" language="javascript">
jQuery(function() {
jQuery('#my_input').attr('autocomplete', 'off');
});
</script>
<input type="text" name="my_input" id="my_input">

autocomplete="off" works in Firefox, but it doesn't work in Chromium browsers on Ubuntu, so you need to check if the browser is a Chromium browser, and if it is use autocomplete="disabled", otherwise use autocomplete="off".
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
$("#mobile").prop("autocomplete", is_chrome ? 'disabled' : 'off');

Simplest way:
Remove name attribute, and add always a different string in autocomplete.
$(document).ready(function () {
setTimeout(function () {
var randomicAtomic = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
$('input[type=text]').removeAttr('name');
$('input[type=text]').attr('autocomplete', randomicAtomic);
}, 1000);
})

use autocomplete = "off" in Html.BeginForm
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "myForm", #autocomplete = "off" }))
{
#Html.EditorFor(model => model.field, new { htmlAttributes = new { #class = "text-box form-control" } })
<input type="submit" value="Save" />
}

Related

autocomplete= off not working in chrome

We are working on one web application in that one payment page is there.
In that we have two Text box one is for Credit Card Number and second one is for Verification Code and it type="Password".
Now problem is when page is load in google-chrome it found type="Password" it load Save email id in Credit Card Textbox and password in Verification Code.
Now try to solve this issue i was try out something like below.
<form autocomplete="off">
<asp:textbox autocomplete="off">
This above try is not work for me. i was googling it but by luck it's not work for me.
It appears that Chrome now ignores autocomplete="off" unless it is on the <form autocomplete="off"> tag since v34.
you can't cheat by create an hidden input over. Auto complete feature will get the first input text to fill data.
Method 1:
<form id="" method="post" action="" autocomplete="off">
<input type="text" style="display:none" />
<input type="password" style="display:none">
<asp:textbox autocomplete="off">
</form>
So put this before your textbox.
<input type="text" style="display:none" />
Method 2:
Change
autocomplete="off"
to
autocomplete="false"
Method 3:
Browser autofill in by readonly-mode.
<input type="password" readonly onfocus="this.removeAttribute('readonly');"/>
Method 4:
For username password combinations. Chrome heuristics looks for the pattern.
<input type="text" onfocus="this.type='password'">
Method 5:
jQuery
if ($.browser.webkit) {
$('input[name="password"]').attr('autocomplete', 'off');
$('input[name="email"]').attr('autocomplete', 'off');
}
This is the only solution that worked for me with both Autocomplete and Chrome's Autofill:
It works also after calling new this.props.google.maps.places.Autocomplete
Add autocomplete="off" on the form tag.
Set autocomplete="none" directly on the input inside the form and set the attribute again on focus.
<form autocomplete="off">
<input type="text" autocomplete="none" onfocus="this.setAttribute('autocomplete', 'none');"/>
</form>
this is works if you want to keep white as your input background color
<input type="password" class="form-control" id="password" name="password" placeholder="Password" readonly onfocus="this.removeAttribute('readonly');" style="background-color: white;">
use this solution
<input type="password" class="form-control auto-complete-off" id="password" name="password" autocomplete="new-password">
Chrome does not support autocomplete="off" at the form level for some input fields.
There are 2 solutions to do so:
In your form, if only two or three fields ignore autocomplete="off", then use the field name itself as the autocomplete value. i.e. autocomplete=
<form:input type="text" id="name" path="name" autocomplete="name"/>
Instead of defining field name manually for each field, use a script for all text typed input at the loading of the page or after.
if ($.browser.chrome) {
$(document).on('focus click tap', 'input', function() {
$(this).attr("autocomplete", 'block');
});
} else {
$(document).on('focus click tap', 'input', function() {
$(this).attr("autocomplete", 'off');
});
}
this solution is no longer working in chrome 95 and above,
Try using a normal input with type text, disable copy and pasting then add a style with property -webkit-text-security to add character mask on typing
#Not that this css property is not universal as mentionned here https://developer.mozilla.org/fr/docs/Web/CSS/-webkit-text-security
This works:
$(document).ready(function () {
setTimeout(() => {
$('input').attr("readonly", 'readonly');
$('input').attr("onfocus", "this.removeAttribute('readonly')");
}, 100);
});
This works well and also compatible with MDL (Material Design Light):
// Fix chrome's ignore on autocomplete=off
$('input[autocomplete=off]').each(function(){
var copy = $(this).clone();
copy.val('');
copy.removeAttr('autocomplete');
copy.insertAfter($(this));
$(this).hide().removeAttr('required id class');
});
This is how I solved the problem.
$("body").on('focus',':input', function (e) {
$(this).attr('autocomplete', 'off');
$(this).attr('autocapitalize', 'off');
$(this).attr('autocorrect', 'off');
$(this).attr('spellcheck', 'false');
});
OR
<input type="text" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false">
Is it not possible to use password type where text type is required?Regardless of the method presented above, Chrome unconditionally handles autocomplete if the name is the same.
So, I used a method to randomly change the name like this.
$(document).on('focus click tap'
, 'input[autocomplete][autocomplete!=""]:not([data-oname][data-oname!=""])'
, function() {
var oname = $(this).attr('name');
var newName = "random string"; // random string
$(this).attr({"data-oname":oname,"name":newName,autocomplete:newName});
// A random string should be set for name and autocomplete above.
}).on('blur', 'input[data-oname][data-oname!=""]', function() {
var oname = $(this).attr('data-oname');
$(this).attr({"name":oname}).removeAttr('data-oname');
});
automcomplete="off" or automcomplete="false"
or Define autocomplete inside Input field
$('input[name="password"]').attr('autocomplete', 'off');//Disable cache
very simple, you can follow this
let elements = document.querySelectorAll('[autocomplete="off"]');
elements.forEach(element => {
element.setAttribute("readonly", "readonly");
element.style.backgroundColor = "inherit";
setTimeout(() => {
element.removeAttribute("readonly");
}, 500);
})
Use autocomplete="new-password" instead of autocomplete="off". This is a newer, more specific value for the autocomplete attribute, which indicates that the field is for a new password, rather than just any input. This can help prevent the browser from auto-filling the field with old passwords.

Call a function after Html5 Validation success

I have Some text boxes and one submit button. I have Used HTML5 'required' validation. Its working fine. Now I want to call a function in button click when HTML5 validation does not find any Error. When The required field is not provided the button click will not call the function.
You can use the form.onsubmit handler. Assuming the form's ID is form:
var form = document.getElementById("form");
form.onsubmit = function() {
//Pre-submission validation.
//Return true or false based on whether the validation passed.
//return false will prevent the submission the form.
};
You're going to need some extra help to do this, it could be in the form of plain javascript. Personally, I'd use jQuery to help out as it will make things easier for you and account for any cross-browser consistencies. Whether or not you want to use jQuery your is choice, whether it's appropriate only for this is another conversation, the following example is just a demonstration.
Here's a hypothetical example using jQuery that achieves your validation listening functionality:
HTML
<form>
<input type="text" class="input-text" required>
<input type="text" class="input-text" required>
<input type="submit" id="submit" class="input-button" disabled>
</form>
​
JS
$textInputs = $('input.input-text');
$textInputs.on('keyup', function() {
var $validTextInputs = $('input.input-text:valid'),
$submit = $('#submit');
console.log($textInputs.length, $validTextInputs.length);
if($textInputs.length === $validTextInputs.length){
//all text fields are valid
$submit.attr('disabled', null);
} else {
//not all text fields are valid
$submit.attr('disabled', '');
}
});​
CSS (only let's us know, visually, when the input is valid)
.input-text:valid {
background: green;
}​
See the example in action here: http://jsfiddle.net/m6QXc/
Use jquery to trigger function after HTML5 form validation
<form id="myForm">
<input type="text" class="input-text" required>
<input type="submit" id="submit" class="input-button" disabled>
</form>
$("myForm").submit(function(){
// Your code
})
Well, you could try this: fiddle example extend it as you need, used jQuery though. You can add whatever you want inside:
$('#exampleForm').submit(function(e){
e.preventDefault();
// here you can call your own js methods, send form with ajax?
// or what ever you want
});

Is there a minlength validation attribute in HTML?

It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?
You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.
Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.
Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>
Yes, there it is. It's like maxlength. W3.org documentation:
http://www.w3.org/TR/html5/forms.html#attr-fe-minlength
In case minlength doesn't work, use the pattern attribute as mentioned by #Pumbaa80 for the input tag.
For textarea:
For setting max; use maxlength and for min go to this link.
You will find here both for max and min.
I used maxlength and minlength with or without required and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
`
minlength attribute is now widely supported in most of the browsers.
<input type="text" minlength="2" required>
But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).
To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:
<input type="text" pattern=".{2,}" required>
There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:
<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
Input with minlength: <input type="text" minlength="2" required name="i1">
<input type="submit" value="Submit">
</form>
<br>
<form action="#">
Input with patern: <input type="text" pattern=".{2,}" required name="i1">
<input type="submit" value="Submit">
</form>
For example, in Chrome (but similar in most browsers), you will get the following error messages:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
by using minlength and
Please match the format requested
by using pattern.
I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.
An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>
Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.
My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.
If the value of the "type" is one of them:
text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)
Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.
For example,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
Or use the "pattern" attribute:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.
For example,
<input type="number" min="100" max="999" placeholder="input a three-digit number">
New version:
It extends the use (textarea and input) and fixes bugs.
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}
I wrote this JavaScript code, [minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}
In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.
Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.
Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.
I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>
If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;
Following #user123444555621 pinned answer.
There is a minlength attribute in HTML5 but for some reason it may not always work as expected.
I had a case where my input type text did not obey the minlength="3" property.
By using the pattern attribute I managed to fix my problem.
Here's an example of using pattern to ensure minlength validation:
const folderNameInput = document.getElementById("folderName");
folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);
function setFolderNameValidityMessage() {
if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
} else {
folderNameInput.setCustomValidity('');
}
}
:root {
--color-main-red: rgb(230, 0, 0);
--color-main-green: rgb(95, 255, 143);
}
form input {
border: 1px solid black;
outline: none;
}
form input:invalid:focus {
border-bottom-color: var(--color-main-red);
box-shadow: 0 2px 0 0 var(--color-main-red);
}
form input:not(:invalid):focus {
border-bottom-color: var(--color-main-green);
box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
<input
type="text"
id="folderName"
placeholder="Your folder name"
spellcheck="false"
autocomplete="off"
required
minlength="3"
maxlength="50"
pattern=".{3,50}"
/>
<button type="submit" value="Create folder">Create folder</button>
</form>
For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern
You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.
Smartest Way for maxlength
$("html").on("keydown keyup change", "input", function(){
var maxlength=$(this).attr('maxlength');
if(maxlength){
var value=$(this).val();
if(value.length<=maxlength){
$(this).attr('v',value);
}
else{
$(this).val($(this).attr('v'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">
I've used the follow tag with numbers:
<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />

Can a form submit be disabled if a HTML file input field is empty?

In a form which contains only a
<input id="fileInput" name="BugReport" type="file" />
input field, I would like to disable the Submit button if the file input is empty (no file was chosen yet). Is there a recommended way to do this?
Add the required attribute to the input. It'll only work in browsers that support it, so you should have a JavaScript alternative (<form onSubmit="if(document.getElementById('fileinput').value == '') return false;"> or something along those lines).
Checking for whether the file input's value should always work.
if (document.getElementById("fileInput").value == "") .....
the true path of the file will be obfuscated for security reasons, but the value should always return something when a file is selected.
You can do it with JavaScript. The following code assumes you have given an id of "s" to the submit button of the form:
document.getElementById("fileInput").onchange = function() {
if(this.value) {
document.getElementById("s").disabled = false;
}
}
Obviously, you'll need to have the submit button disabled to start off. For example:
<input type="submit" id="s" disabled>
With this the best way is to have Javascript validate all the inputs as they are changed. So as the input gets changed (you can use the on change event) in Javascript enable or disable the button depending.
<input id="fileInput" name="BugReport" type="file" onchange="validateForm()"/>
This should call the javascript button which will check the input is it has a valid file and if so enable the submit button.
You can do this using jQuery
<script src="/Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
$(function () {
$('#submit').attr("disabled", true);
$('#fileInput').change(function () {
if ($('#fileInput').val().length == 0)
$('#submit').attr("disabled", true);
else
$('#submit').attr("disabled", false);
});
});
</script>
<input id="fileInput" name="BugReport" type="file" />
<input id="submit" type="submit" />
hope this helps
yeah, you can add something like:
<input type="submit" onclick="if (window.getElementById('fileInput').value == '') return false" />
or start with a disabled submit button and enable it when the file input is clicked and the value is different than the empty string.
check this jsbin to see what the value of a file input is (its a 'fakepath' and the name of the file)
If you are using HTML5 just add required inside input tag:
<input type='file' required />
Example:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>

Set a form's action attribute when submitting?

How do I change a form's action attribute right after clicking the submit button?
<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />
Or you can modify it from outside the form, with javascript the normal way:
document.getElementById('form_id').action = 'somethingelse';
There's a simple way to do this if you only need to support modern browsers: on your submit button, add a formaction="/alternate/submit/url" attribute like so:
<form>
[fields]
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
It also works on <button> tags.
The gotcha is that old versions of IE (<10) and the Android Browser (<4.0) do not support it. So, if you need to support older browsers, then the existing JS answers will probably work better for you.
More info: http://www.wufoo.com/html5/attributes/13-formaction.html
You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.
Something like this:
<form id="whatever" name="whatever" onSubmit="return xyz();">
Here is your entire form
<input type="submit">
</form>;
<script type=text/javascript>
function xyz() {
document.getElementById('whatever').action = 'whatever you want'
}
</script>
Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.
Attach to the submit button click event and change the action attribute in the event handler.
You can do that on javascript side .
<input type="submit" value="Send It!" onClick="return ActionDeterminator();">
When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.
function ActionDeterminator() {
if(document.myform.reason[0].checked == true) {
document.myform.action = 'http://google.com';
}
if(document.myform.reason[1].checked == true) {
document.myform.action = 'http://microsoft.com';
document.myform.method = 'get';
}
if(document.myform.reason[2].checked == true) {
document.myform.action = 'http://yahoo.com';
}
return true;
}
HTML5's formaction does not work on old IE browsers. An easy fix, based on some of the responses above, is:
<button onclick="this.form.action='/PropertiesList';"
Account Details </button>
You can try this:
<form action="/home">
<input type="submit" value="cancel">
<input type="submit" value="login" formaction="/login">
<input type="submit" value="signup" formaction="/signup">
</form>