When using the xhtml1-transitional.dtd doctype, collecting a credit card number with the following HTML
<input type="text" id="cardNumber" name="cardNumber" autocomplete='off'/>
will flag a warning on the W3C validator:
there is no attribute "autocomplete".
Is there a standards-compliant way to disable browser auto-complete on sensitive fields in a form?
Here is a good article from the MDC which explains the problems (and solutions) to form autocompletion.
Microsoft has published something similar here, as well.
To be honest, if this is something important to your users, 'breaking' standards in this way seems appropriate. For example, Amazon uses the 'autocomplete' attribute quite a bit, and it seems to work well.
If you want to remove the warning entirely, you can use JavaScript to apply the attribute to browsers that support it (IE and Firefox are the important browsers) using someForm.setAttribute( "autocomplete", "off" ); someFormElm.setAttribute( "autocomplete", "off" );
Finally, if your site is using HTTPS, IE automatically turns off autocompletion (as do some other browsers, as far as I know).
Update
As this answer still gets quite a few upvotes, I just wanted to point out that in HTML5, you can use the 'autocomplete' attribute on your form element. See the documentation on W3C for it.
I would be very surprised if W3C would have proposed a way that would work with (X)HTML4. The autocomplete feature is entirely browser-based, and was introduced during the last years (well after the HTML4 standard was written).
Wouldn't be surprised if HTML5 would have one, though.
Edit: As I thought, HTML5 does have that feature. To define your page as HTML5, use the following doctype (i.e: put this as the very first text in your source code). Note that not all browsers support this standard, as it's still in draft-form.
<!DOCTYPE html>
HTML 4: No
HTML 5: Yes
The autocomplete attribute is an enumerated attribute. The attribute
has two states. The on keyword maps to the on state, and the off
keyword maps to the off state. The attribute may also be omitted. The
missing value default is the on state. The off state indicates that by
default, form controls in the form will have their autofill field name
set to off; the on state indicates that by default, form controls in
the form will have their autofill field name set to "on".
Reference: W3
No, but browser auto-complete is often triggered by the field having the same name attribute as fields that were previously filled out. If you could rig up a clever way to have a randomized field name, autocomplete wouldn't be able to pull any previously entered values for the field.
If you were to give an input field a name like "email_<?= randomNumber() ?>", and then have the script that receives this data loop through the POST or GET variables looking for something matching the pattern "email_[some number]", you could pull this off, and this would have (practically) guaranteed success, regardless of browser.
No, a good article is here in Mozila Wiki.
I would continue to use the invalid attribute. I think this is where pragmatism should win over validating.
How about setting it with JavaScript?
var e = document.getElementById('cardNumber');
e.autocomplete = 'off'; // Maybe should be false
It's not perfect, but your HTML will be valid.
I suggest catching all 4 types of input:
$('form,input,select,textarea').attr("autocomplete", "off");
Reference:
http://www.w3.org/Submission/web-forms2/#the-autocomplete
http://dev.w3.org/html5/markup/input.html
If you use jQuery, you can do something like that :
$(document).ready(function(){$("input.autocompleteOff").attr("autocomplete","off");});
and use the autocompleteOff class where you want :
<input type="text" name="fieldName" id="fieldId" class="firstCSSClass otherCSSClass autocompleteOff" />
If you want ALL your input to be autocomplete=off, you can simply use that :
$(document).ready(function(){$("input").attr("autocomplete","off");});
Another way - which will also help with security is to call the input box something different every time you display it: just like a captha. That way, the session can read the one-time only input and Auto-Complete has nothing to go on.
Just a point regarding rmeador's question of whether you should be interfering with the browser experience: We develop Contact Management & CRM systems, and when you are typing other people's data into a form you don't want it constantly suggesting your own details.
This works for our needs, but then we have the luxury of telling users to get a decent browser:)
autocomplete='off'
autocomplete="off" this should fix the issue for all modern browsers.
<form name="form1" id="form1" method="post" autocomplete="off"
action="http://www.example.com/form.cgi">
[...]
</form>
In current versions of Gecko browsers, the autocomplete attribute works perfectly. For earlier versions, going back to Netscape 6.2, it worked with the exception for forms with "Address" and "Name"
Update
In some cases, the browser will keep suggesting autocompletion values even if the autocomplete attribute is set to off. This unexpected behavior can be quite puzzling for developers. The trick to really forcing the no-autocompletion is to assign a random string to the attribute, for example:
autocomplete="nope"
Since this random value is not a valid one, the browser will give up.
Documetation
Using a random 'name' attribute works for me.
I reset the name attribute when sending the form so you can still access it by name when the form is sent. (using the id attribute to store the name)
Note that there's some confusion about location of the autocomplete attribute. It can be applied either to the whole FORM tag or to individual INPUT tags, and this wasn't really standardized before HTML5 (that explicitly allows both locations). Older docs most notably this Mozilla article only mentions FORM tag. At the same time some security scanners will only look for autocomplete in INPUT tag and complain if it's missing (even if it is in the parent FORM). A more detailed analysis of this mess is posted here: Confusion over AUTOCOMPLETE=OFF attributes in HTML forms.
Not ideal, but you could change the id and name of the textbox each time you render it - you'd have to track it server side too so you could get the data out.
Not sure if this will work or not, was just a thought.
I think there's a simpler way.
Create a hidden input with a random name (via javascript) and set the username to that. Repeat with the password. This way your backend script knows exactly what the appropriate field name is, while keeping autocomplete in the dark.
I'm probably wrong, but it's just an idea.
if (document.getElementsByTagName) {
var inputElements = document.getElementsByTagName("input");
for (i=0; inputElements[i]; i++) {
if (inputElements[i].className && (inputElements[i].className.indexOf("disableAutoComplete") != -1)) {
inputElements[i].setAttribute("autocomplete","off");
}
}
}
I MADE THIS WORK IN 2020!
I basically create a css class that applies -webkit-text-security to my inputs.
Here's the link to a more recent discussion:
https://stackoverflow.com/a/64471795/8754782
This solution works with me:
$('form,input,select,textarea').attr("autocomplete", "nope");
if you want use autofill in this region: add autocomplete="false" in element
ex:
<input id="search" name="search" type="text" placeholder="Name or Code" autcomplete="false">
Valid autocomplete off
<script type="text/javascript">
/* <![CDATA[ */
document.write('<input type="text" id="cardNumber" name="cardNumber" autocom'+'plete="off"/>');
/* ]]> */
</script>
Related
I have a form where an admin can add candidates. When I run my application in IE8, and click on reset button, it removes placeholder from all the fields. I am using placeholder.js to support placeholder property in IE8.
Here is my reset function ...
function resetCandidateData(){
$("#addCandidateForm")[0].reset();
}
My form is like that ....
<form name="addCandidateForm" id="addCandidateForm" method="Post">
<input type="text" name="cname" id="cname" class="inputBox bdr-radius5" placeholder="Enter candidate name" autocomplete="off"/>
.....
.....
<span class="global-button" onclick="resetCandidateData();">Reset</span>
</form>
First time when page refresh, it showing placeholder in each of my textfields in IE8 but after reset all are vanish. Please help.
I don't know anything about the specific placeholder.js library that you're using, and you didn't provide a link, so I can't even tell which one it is.
However, it sounds to me like you need to use a better placeholder script.
If resetting the fields clears the placeholders, then it means that the script is using the field value to display the placeholder.
This is fine, but does have some limitations, in particular as you've seen with resetting the fields, but it also means that you can't have placeholders on a password field (because they would show up as stars like the password itself), and you can't easily have the placeholder styled differently to the field values.
For all these reasons, I prefer a placeholder script that uses a different technique - eg putting the placeholder in its own element and displaying it on top of (or behind) the input field, rather than actually using the input field itself for the placeholder.
So therefore my advice is to find an alternative placeholder script. It should be fairly straightforward to take one out and plug another one in, and there are plenty of them out there to pick from. Take a look here for a list of some of the best ones.
Hope that helps.
Change your resetCandidateData function to
function resetCandidateData(){
$("#addCandidateForm")[0].reset();
$.Placeholder.init();
}
It should restore the placeholders.
Background
I've got a couple of jQuery functions that set a search field to contain the word "Search" and clear it / reset it when the field is clicked in and out of....
// Search Box Placeholder
jQuery('#q').focus(function() {
if(jQuery(this).val() == 'Search') {
jQuery(this).val('');
}
else if(jQuery(this).val() == '') {
jQuery(this).val('Search');
}
});
jQuery('#q').blur(function() {
if(jQuery(this).val() == '') {
jQuery(this).val('Search');
}
});
jQuery('#q').val('Search');
Question ?
The only issue is I'm not sure how to clear the word Search if the search form is submitted without an alternative search term being set. Is there a way to check and clear the contents before the form submission if the contents are equal to 'Search' ?
You can prevent the submission of form if the value is equal to 'Search'.
$('form').on('submit', function(){
return $('#q').val() !== 'Search';
});
If you want to support older browsers that do not support placeholder attribute, you can also use a plugin.
https://github.com/parndt/jquery-html5-placeholder-shim
The key to finding the answer to this kind of thing is often more about knowing the terminology than anything else.
In this case, if you'd searched for the word "polyfill" rather than "mimic", you'd have found the solution. "Polyfill" is web developer speak for a browser script that implements a feature of newer browsers so that it works in older browsers.
The placeholder feature is a classic one for this, because it's very useful and easily done.
Modernizr is a Javascript library that aims to simplify the process of working with polyfills. It detects whether a feature is supported, so that you can know whether or not to load the polyfill for that feature.
It's a useful tool, but the main reason I mention Modernizr is because they also maintain a big list of polyfill scripts.
Click that link and search for 'placeholder'... you'll find there's a whole stack of scripts that can do it for you. Just pick the one that works best for you, or crib from the techniques they use.
Hope that helps.
An alternative you may want to consider is not adding the placeholder text as the value of the control. Instead, use another element, possibly the input label or a span, absolutely positioned over the text input, and hide it when the corresponding input has the control. Also, when the user clicks on this label, you should hide it and set the focus to the control. This will also let you change the placeholder color.
I have a input text box disabled:
<input type="text" name="name" disabled="disabled" />
In IE and in Chrome you can copy and paste the value populated in that input field but in Firefox you cannot.
Firefox does not allow clipboard manipulation through JavaScript for valid security concerns.
Any suggestion? Is there a work around this?
readonly="readonly" will do the job
it should be supported by the major browsers
I don't like using readonly="readonly", ever. It leaves the field focusable and reachable via tab keypress and, if, god forbid, the user hits the backspace key while the read-only field is focused, then most browsers treat it like the user hit the 'back' button and bring up the previously viewed page. Not what you want to see happen when you're filling out a large form, especially if you are using some archaic browser that doesn't preserve the form data when you hit the 'next' button to return to it. Also very, very bad when using some single-page web application, where 'back' takes you to a whole other world, and 'next' doesn't even restore your form, much less its data.
I've worked around this by rendering DIVs instead of input fields when I need the field disabled (or PRE instead of a textarea). Not always easy to do dynamically but I've managed to make fairly short work of it with AngularJS templates.
If you have time, head over to the Mozilla Bugzilla and ask them to fix it.
tl;dr: Support for selecting and copying text in a disabled field is unreliable; use the readonly attribute or a non-input element, such as a <span> instead, if this functionality is necessary. Use JavaScript to modify the behavior of the readonly input to prevent unwanted behavior such as going back a page when someone hits the backspace key while the readonly input has focus.
*UPDATE: 2018.12.24
The spec has changed since this answer was originally posted (thanks to Wrightboy for pointing this out); it now includes the following caveat with regards to disabled fields:
Any other behavior related to user interaction with disabled controls, such as whether text can be selected or copied, is not defined in this standard.
— https://html.spec.whatwg.org/multipage/input.html#the-readonly-attribute
Disabled fields still cannot receive focus nor click events.
Because the standard does not define whether or not text within disabled controls can be selected or copied and because at least one major browser doesn't support that functionality, it's probably best to avoid relying on that behavior.
Original Answer
This is the expected behavior for a disabled field (as of the original date of this answer). IE and Chrome are being generous, but Firefox is behaving appropriately.
If you want to prevent the user from changing the value of the field, but you still want them to be able to read it, and/or copy it's value, then you should use the readonly attribute. This will allow them to set focus to the element (necessary for copying), and also access the field via the tab button.
If you are concerned about a user accidentally hitting the backspace button inside the readonly field and causing the browser to navigate back a page, you can use the following code to prevent that behavior:
document.addEventListener("DOMContentLoaded", function() {
var inputs = document.querySelectorAll('[readonly]');
for(var i=0; i < inputs.length; i++){
inputs[i].addEventListener('keydown', function(e){
var key = e.which || e.keyCode || 0;
if(key === 8){
e.preventDefault();
}
})
}
});
<input value="Hello World" readonly=readonly />
As quick answer, one can have another not disabled element to enable + copy/paste + redisable your input text, like this:
$('#btnCopy').click(function(){
$('#txtInputDisabled').removeAttr('disabled');
$('#txtInputDisabled').select();
document.execCommand("copy");
$('#txtInputDisabled').attr('disabled','disabled');
});
You can se my complete response to this post
Refer to my post to the same question. It does the following:
Makes the textbox just like readonly without using the readonly attribute on the input tag, but will honor tab index and set focus
Supports all clipboard functions win and mac with mouse or keyboard
Allows undo, redo and select all
Restrict HTML input to only allow paste
You can accomplish this in share point by utilizing the contenteditable attribute as follows with jquery.
$("#fieldID").attr("contenteditable", "false");
This will allow the user to highlight the text and copy it but will not allow them to enter anything in the field.
i have the following html :
<input type="text" id="searchbox" name="q" value="Search Pictures..." onclick=" if(this.value=='Search Pictures...'){this.value='';}" />
It's works when i open the page for the first time, but when i type something and search , then i come back to the page, or refresh, i find the past keyword still sticky instead of "Search Pictures..."
Any available tag to avoid this problem ?
Thanks
If you've set the value on the tag to "Search Pictures..." as you have, then whenever the page loads without having somehow persisted a newer value beforehand, you will get the "Search Pictures..." as the value.
To persist input data, you have several ways available depending on what environment you're developing with.
By the way... don't write:
this.value === 'blah blah, copy of text from value attribute'
Just simply use defaultValue property:
this.value == this.defaultValue
It's much simpler and cleaner.
I guess it's on firefox.
You can add the attribute autocomplete="off"
HTTP is stateless and does not persist form values between requests.
Every single time you load the page the 'hard-coded' VALUE 'Search Pictures...' will replace anything in the input element from the previous request. You need to persist the value by retrieving the posted value from the form collection and writing it back in. How you do this depends on the platform you are working on - presumably you are using some kind of server-side framework or language (e.g. PHP or ASP.NET)?
Hi all I am working on a contact or phone book application. So currently I am working on searching for records. Now I have this form with certain elements/fields being required or mandatory while others are optional.
So I wrote a very simple javascript function to check if those required fields are missing or not. It works greate on firefox and chrome however not in IE.
It seems that the if clause is failing in my js in IE because wheather i enter the required fields or don't enter the required fields i get the alert message telling me to enter the rquired fields. Mind you this doesn't happen in firefox only IE. So I'll put some relevant code bits here for you to have a look hoping you can help me out here:
head
some css code
...
<script type="text/javascript">
function disp_confirm()
{
if (document.contractor_phonebook_form.Service.value == "" || document.....etc.)
{
javascript:alert('Please enter all necessary fields!');
return false;
}
else
{
return true;
}
}
</script>
end of head beginning of body
<form action='<?php $PHP_SELF; ?>' method='post' name="contractor_phonebook_form" target="_self" onSbumit="return disp_confirm()">
some of the form elements are autofilled from a database query using mysql and php to fill the form elements. while others are simple drop down menus.
<select name="Service">
... etc..
hopefully you have an idea of what i have here and why does IE always give me the alert message please fill in the required fields wheahter I ENTER OR DON'T ENTER any form fields..
thank you in advance again..
OKAY I found the answer to my problem... Most browsers would detect the value of the option fields automatically meaning what I originally had was this:
<select name ="Service">
<option>NOCC</option>
<option>HVAC</option>
....etc.
</select>
however IE was always getting null values since I didn't explicitly specify the value attribute to the element tag. So all I did was change my code from that on top to the following:
<select name="Service">
<option value="NOCC">NOCC</option>
<option value="HVAC">HVAC</option>
....etc..
</select>
and now works fine in IE. Strange enough most browsers are able to detect the value attribute by looking at the option tag display however IE requires that you specifically define the value attribute otherwise will look at it as blank or null. and that's why my if clause was failing in IE because i didn't specify the value attribute and hence it was always blank even when I did choose a value from the drop down menu it still saw it as blank.
thank you all for your help I definately benefited by learning something new from your posts like JQuery.
cheers
There is a nice jQuery cross browser solution and provides validation for email addresses, dates, other common functions. You can define a common div where your errors can be displayed.
I've used this with Asp.net and had little trouble adapting it to my needs. There are quite a few users here at SO that have used this solution.
You should be calling alert like a normal function, without writing javascript: first.
However, your problem is that IE implements the value property for select elements differently.
You need to check whether any of the options' selected property is true.
This is easiest to do using jQuery, like this:
if ($('#service').val() === ""
|| $('#somethingElse').val() === "") {
alert("Please enter all necessary fields.");
return false;
} else
return true;
You dont need to put javascript: before your alert(); function.