How to I disable form autofill in all browsers? - html

I've looked through a number of posts all pointing towards different ways of using the autocomplete property, but I have yet to have this work in all my browsers. I've seen some really ugly workarounds such as this, but I'm looking for something that is clean and easy.
What is a good way to disable text field autofill on all (or at least, most) common browsers?

The following code will disable autocomplete in FF, IE, and Chrome.
<script>
$(document).ready(function () {
// IE & FF
$('input').attr('autocomplete', 'off');
// Chrome
if ( $.browser.webkit ) {
$('input').attr('autocomplete', 'new-password');
}});
</script>

Enabling Autocomplete on both form and input fields (with the "off" value) for the sake of those law-abiding browsers that do play by the rules is always a good beginning - also for the unlikely event that one day "other" browser...s may feel like compliance isn't all bad.
Until that day hacks are needed. I've noticed that Chrome looks for matching data in at least three places: Labels (contexts), Names and Placeholders. If the Name field is missing from input fields it will look in both Labels and placeholders, but if the Name field is present it will only look in Name and Placeholder.
This script utilize the "form-control" class from Bootstrap on input fields that must be guarded from Autocomplete. Use any other class or filter you like. Also assuming that Placeholders are in use - just remove that part if not.
$(document).ready(function() {
// Begin
var this_obj = null, this_placeholder = null, this_name = null;
$(".form-control").focus(function() {
this_obj = this;
this_name = $(this).prop("name");
this_placeholder = $(this).attr("placeholder");
$(this).prop("name", "NaN" + Math.random());
$(this).attr("placeholder", "...");
}).blur(function() {
$(this_obj).prop("name", this_name);
$(This_obj).attr("placeholder", this_placeholder);
});
// End
});
Note: Leaving the Placeholder empty might actually inadvertently trigger the Autocomplete function as empty assignments are apparently ignored.
The two variables this_name and this_placeholder may be avoided as they are accessible through this_obj, but I like to keep them around for the sake of readability and clarity.
The Script is erm.. quite unobtrusive, as it cleans up after itself and it only requires one matching class or attribute.
It works in Version 68.0.3440.106 (Officiel version) (64-bit), IE11 11.228.17134.0 and Firefox 61.0.2 (64-bit). Sorry, haven't tested others.

Add a class to all your input tags, suppose no-complete
And in your js file add following code:
setTimeout(function (){
$('.no-complete').val ("");
},1);

Related

cannot get value when I click the auto select [duplicate]

When you have saved username and password for some site Chrome will autofill that username and password, but if you try to get the value for the password input field it is empty String even though there is value there ******.
If you click somewhere on the page no mater where the value of the input type="password" will be filled.
This is Fiddle user/pass of the structure of the html and the console.log command. It cannot be seen here but it can be reproduced on every page that has login form and the username and password are autofilled on the load of the page. If you inspect the value of the field before clicking anywhere else on the site it will be empty String.
This is not the case in Firefox or Internet Explorer it will fill the value of the input element with the password.
I am using Windows 7 Ultimate 64-bit OS and Google Chrome version is 48.0.2564.97 m
Is this normal behavior, bug or?
UPDATE:
If you click on F5 to reload the page and inspect the password field the value for password will be there. If you click the reload button in Chrome in top left corner the value for the password field will be empty string.
This seems to be a bug in Chrome. When Chrome auto-fills a password on an initial page load (but not a refresh), the value appears in the form field on-screen, but querying passwordField.value in Javascript returns an empty string. If you depend on seeing that value in Javascript, this prevents you from doing so. Once the user does any other action on the page, such as clicking anywhere on the page, the value suddenly becomes visible to Javascript.
I'm not actually 100% sure if this is a bug, or if there is a security reason for doing this such as preventing a hidden frame from stealing your password by tricking the browser into filling it in.
A workaround that we have used is to detect the background color change that Chrome makes to fields that it has auto-filled. Chrome colors the background of auto-filled fields yellow, and this change is always visible to Javascript even when the value is not. Detecting this in Javascript lets us know that the field was auto-filled with a value, even though we see the value as blank in Javascript. In our case, we have a login form where the submit button is not enabled until you fill in something in the password field, and detecting either a value or the auto-fill background-color is good enough to determine that something is in the field. We can then enable the submit button, and clicking the button (or pressing enter) instantly makes the password field value visible to Javascript because interacting with the page fixes the problem, so we can proceed normally from there.
Working Answer as of July 8, 2016
Adam correctly stated this is a bug (or intended behavior). However, none of the previous answers actually say how to fix this, so here is a method to force Chrome to treat the autocompleted value as a real value.
Several things need to happen in order, and this needs to only run in Chrome and not Firefox, hence the if.
First we focus on the element. We then create a new TextEvent, and run initTextEvent, which adds in a custom string that we specify (I used "#####") to the beginning of the value. This triggers Chrome to actually start acting like the value is real. We can then remove the custom string that we added, and then we unfocus.
Code:
input.focus();
var event = document.createEvent('TextEvent');
if ( event.initTextEvent ) {
event.initTextEvent('textInput', true, true, window, '#####');
input.dispatchEvent(event);
input.value = input.value.replace('#####','');
}
input.blur();
Edit August 10, 2016
This only works right now in Chrome on Windows and Android. Doesn't work on OSX. Additionally, it will stop working at all in Sept 2016, according to:
https://www.chromestatus.com/features/5718803933560832
Also, I've opened a Chromium ticket.
https://bugs.chromium.org/p/chromium/issues/detail?id=636425
As of August 12, a member of the Chrome team said on the above ticket that the behavior won't be changing because they don't consider it a bug.
Long-term Work-Around Suggestion:
That said, the current behavior has been tweaked from when it was first implemented. The user no longer has to interact with the password input for the value to be reported. The user now just needs to interact (send a mouse or keyboard event) with any part of the page. That means that while running validation on pageload still won't work, clicking on a submit button WILL cause Chrome to correctly report the password value. The work-around then, is to revalidate all inputs that might be autocompleted, if that is what you are trying to do, on submit.
Edit December 13, 2016:
A new Chromium ticket has been opened and is being received better. If interested in changing this behavior of Chrome's, please star this new ticket:
https://bugs.chromium.org/p/chromium/issues/detail?id=669724
Continuing from what Kelderic said, here's my work around. Like a lot of people, I don't need the actual password value. I really just need to know that the password box has been autofilled, so that I can display the proper validation messages.
Personally, I would not use suggested solution to detect the background color change cause by Chrome's autofill. That approach seems brittle. It depends on that yellow color never changing. But that could be changed by an extension and be different in another Blink based browser (ie. Opera). Plus, there's no promise Google wont use a different color in the future. My method works regardless of style.
First, in CSS I set the content of the INPUT when the -webkit-autofil pseudo-class is applied to it:
input:-webkit-autofill {
content: "\feff"
}
Then, I created a routine to check for the content to be set:
const autofillContent = `"${String.fromCharCode(0xFEFF)}"`;
function checkAutofill(input) {
if (!input.value) {
const style = window.getComputedStyle(input);
if (style.content !== autofillContent)
return false;
}
//the autofill was detected
input.classList.add('valid'); //replace this. do want you want to the input
return true;
}
Lastly, I polled the input to allow the autofill time to complete:
const input = document.querySelector("input[type=password]");
if (!checkAutofill(input)) {
let interval = 0;
const intervalId = setInterval(() => {
if (checkAutofill(input) || interval++ >= 20)
clearInterval(intervalId);
}, 100);
}
It is amazing that in 2021 this has not been solved in Chrome yet, I have had issue with autocomplete since 2014 and still nothing.
Chrome functionality autocomplete is misleading for the user, I do not know what are they trying to achieve but does not look good.
As it is now, form appears showing auto-completed text (user/email/pass) to the user, but in the background html - values are not inside of the elements.
As values are not in fields custom validation will disable submit button.
Script that checks fields values will say value is null, which is even more confusing for the user as s/he can see text is there, and can assume it is valid, leading to confusing delete-one insert one character. (Embarrassingly, I have to admit I did not know that you need to click in the body of the HTML, so I wonder how many users don not know the same)
In my case I wanted to have empty field always and then fount out it is just needlessly spent time to make it work.
If we try autocomplete=off we will discover that it is not working. And to validate fields and let say enable button we need to do some trickery.
(Have in mind that I have tried autocomplete=password new-password) and other type of Hocus-Pocus trickery from official resource.
At the end I have done this.
<script>
$('#user').value = ' '; //one space
$('#pass').value = ' '; // one space - if this is empty/null it will autopopulate regardless of on load event
window.addEventListener('load', () => {
$('#user').value = ''; // empty string
$('#pass').value = ''; // empty string
});
</script>
So, it will blink for a split second in some cases in password field with * not ideal but :/ ...
Here's my solution to this issue:
$(document).ready(function(){
if ( $("input:-webkit-autofill").length ){
$(".error").text("Chrome autofill detected. Please click anywhere.");
}
});
$(document).click(function(){
$(".error").text("");
});
Basically, clicking makes the input visible to the user, so I ask the user to click and when they do, I hide the message.
Not the most elegant solution but probably the quickest.
$(document).ready
does not wait for autofill of browser, it should be replaced by
$(window).on("load", checkforAutoFill())
Another option as of Dec. 16 / Chrome 54
I can't get the value of the password field, but, after "a short while", I can get the length of the password by selecting it, which is sufficient for me to enable the submit button.
setTimeout(function() {
// get the password field
var pwd = document.getElementById('pwd');
pwd.focus();
pwd.select();
var noChars = pwd.selectionEnd;
// move focus to username field for first-time visitors
document.getElementById('username').focus()
if (noChars > 0) {
document.getElementById('loginBtn').disabled = false;
}
}, 100);
The workaround specified by Adam:
... detect the background color change that Chrome makes to fields that it has auto-filled. Chrome colors the background of auto-filled fields yellow, and this change is always visible to Javascript even when the value is not. Detecting this in Javascript lets us know that the field was auto-filled with a value, even though we see the value as blank in Javascript
I did like this:-
getComputedStyle(element).backgroundColor === "rgb(250, 255, 189)"
where rgb(250, 255, 189) is the yellow color Chrome applies to auto filled inputs.
I have found a solution to this issue that works for my purposes at least.
I have a login form that I just want to hit enter on as soon as it loads but I was running into the password blank issue in Chrome.
The following seems to work, allowing the initial enter key to fail and retrying again once Chrome wakes up and provides the password value.
$(function(){
// bind form submit loginOnSubmit
$('#loginForm').submit(loginOnSubmit);
// submit form when enter pressed on username or password inputs
$('#username,#password').keydown(function(e) {
if (e.keyCode == 13) {
$('#loginForm').submit(e);
return false;
}
});
});
function loginOnSubmit(e, passwordRetry) {
// on submit check if password is blank, if so run this again in 100 milliseconds
// passwordRetry flag prevents an infinite loop
if(password.value == "" && passwordRetry != true)
{
setTimeout(function(){loginOnSubmit(e,true);},100);
return false;
}
// login logic here
}
Just wrote an angular directive related to this. Ended up with the following code:
if ('password' == $attrs.type) {
const _interval = $interval(() => { //interval required, chrome takes some time to autofill
if ($element.is(':-webkit-autofill')) { //jQuery.is()
//your code
$interval.cancel(_interval);
}
}, 500, 10); //0.5s, 10 times
}
ps: it wont detect 100% of the times, chrome might take longer than 5 seconds to fill the input.
Chrome's intended behavior is that an auto-filled password has an empty value in the DOM until the user interacts with the frame in some way, at which point chrome actually populates the value. Until this point any client side validation or attempt to ajax submit the form will see the password as empty.
This 'populate password value on frame interaction' behavior is inconsistent. I've found when the form is hosted in a same-origin iframe it only operates on the first load, and never on subsequent loads.
This is most evident on ajax forms where the autocomplete password populates on first load, however if that password is invalid and the ajax submission re-renders the form DOM, the autocompleted password re-appears visually but the value is never populated, irrespective of interaction.
None of the workarounds mentioned such as triggering blur or input events worked in this scenario. The only workaround I've found is to reset the password field value after the ajax process re-renders the form, e.g.:
$('input[type="password"]').val("");
After the above, Chrome actually autocompletes the password again but with the value actually populated.
In my current use case I'm using ASP.NET's Ajax.BeginForm and use the above workaround in the AjaxOptions.OnSuccess callback.
$element.is("*:-webkit-autofill")
works for me
With Angular, the new behaviour in Chrome (only allowing autofilled values to be read after the user has interaction with the page) manifests itself as an issue when you're using Angular's validation functionality in certain scenarios (for e.g using standard method/action attributes on the form). As the submit handler is executed immediately, it does not allow the form validators to capture the autofilled values from Chrome.
A solution I found for this to explicitly call the form controllers $commitViewValue function in the submit handler to trigger a revalidation before checking form.$valid or form.invalid etc.
Example:
function submit ($event) {
// Allow model to be updated by Chrome autofill
// #see http://stackoverflow.com/questions/35049555/chrome-autofill-autocomplete-no-value-for-password
$scope.loginModule.$commitViewValue();
if ($scope.loginModule.$invalid) {
// Disallow login
$scope.loginModule.$submitted = true;
$event.preventDefault();
} else {
// Allow login
}
}
Although this is working for us so far, I would be very interested if someone has found another, more elegant work around for the issue.
var txtInput = $(sTxt);
txtInput.focus();
txtInput.select();
This solution worked in my case.
Using jQuery 3.1.1.
If you want make input to be seen as fulfilled, try to trigger blur on it:
$('input[type="password"]').blur();
The autocomplete feature has successfully disabled.
It Works!
[HTML]
<div id="login_screen" style="min-height: 45px;">
<input id="password_1" type="text" name="password">
</div>
[JQuery]
$("#login_screen").on('keyup keydown mousedown', '#password_1', function (e) {
let elem = $(this);
if (elem.val().length > 0 && elem.attr("type") === "text") {
elem.attr("type", "password");
} else {
setTimeout(function () {
if (elem.val().length === 0) {
elem.attr("type", "text");
elem.hide();
setTimeout(function () {
elem.show().focus();
}, 1);
}
}, 1);
}
if (elem.val() === "" && e.type === "mousedown") {
elem.hide();
setTimeout(function () {
elem.show().focus();
}, 1);
}
});
To me none of this solutions seemed to work.
I think this is worth mentioning that if you want to use it for CSS styling you sould use -webkit-autofill property like this:
input:-webkit-autofill~.label,
input:-webkit-autofill:hover~.label,
input:-webkit-autofill:focus~.label
input:focus~.label,
input:not(.empty)~.label {
top: -12px;
font-size: 12px;
color: rgba(0, 0, 0, .4);
font-weight: 600
}
My solution comparing my css to the chrome autocomplete color...
$('input, select, textarea').each(function(){
var inputValue = $(this).val();
if ( inputValue != "" || $(this).css("background-color") != "rgba(255, 255, 255, 0)") {
$(this).parents('.form-group').addClass('focused');
}
});
I tried all the solutions and wasn't working for me so i came up with this.
My problem is i have an input that move the placeholder top when it is filled, off course this is not working when Chrome autofill it.
Only tested in Chrome :
setTimeout(function () {
var autofilled = document.querySelectorAll('input:-webkit-autofill');
for (var i = 0; i < autofilled.length; i++) {
Do something with your input autofilled
}
}, 200);
My version is 95.0.4638.69
I'm facing a similar issue and I solved it by changing my form's name from "login-form" to another name which does not mean anything and solve it. Reason why I didn't remove name attribute is because if I remove name attribute Chrome will look up to id attribute and do the same thing.
Option using onanimationstart event (ReactJs) - Mar 22
I could avoid the needing of verifying periodically if the input was autofilled, as described above using setInterval, by taking advantage of the onanimationstart event. I don't know if it will work in every case, but definitely did the trick for me.
I'll provide a code sample in ReactJs, it may be explanatory enough to be transposed to another context.
First of all, is necessary to add in your input the onAnimationStart property, in such a way that the event is passed as parameter to your function, as following below.
<input
className={componentClass}
placeholder={placeholder}
onChange={handleChange}
onFocus={onFocus}
onMouseEnter={onHover}
onMouseLeave={onHover}
onBlur={onBlur}
disabled={disabled}
name={name}
value={value}
onAnimationStart={e => this.onAnimationStart(e)}
/>
Then let's proceed to the onAnimationStart function body.
onAnimationStart(event) {
// on autofill animation
if (event.animationName === 'onAutoFillStart') {
event.target?.labels[0].classList.add('grm-form__isAutofilled');
}
}
First I verified if the animation name was actually the auto-fill animation, and then I added a class to the first label of my input, this is my use case but can be adapted to solve different problems.
Just set the autocomplete attribute to username for the username field and new-password for the password field;
<input type="text" id="username" autocomplete="username">
<input type="password" id="password" autocomplete="new-password" >
You mentioned:
If you click somewhere on the page no matter where the value of the input type="password" will be filled.
Which is why I simply use $('body').click(); to simulate this first click, after which the value is available in JavaScript.
Also, I set autocomplete="new-password" on my signup form password field, so that the field is not autofilled and users have to fill in a new password.
See this Google Developers page for more information.
It's not a bug. It's a security issue. Imagine if one could just use javascript to retrieve autofilled passwords without the users' acknowledgment.

CSS Selector Case Insenstive [duplicate]

If I have an HTML element <input type="submit" value="Search" /> a css selector needs to be case-sensitive:
input[value='Search'] matches
input[value='search'] does not match
I need a solution where the case-insensitive approach works too. I am using Selenium 2 and Jquery, so answers for both are welcome.
CSS4 (CSS Selector Level 4) adds support for it:
input[value='search' i]
It's the "i" at the end which does the trick.
Broader adoption started mid-2016: Chrome (since v49), Firefox (from v47?), Opera and some others have it. IE not and Edge since it uses Blink. See “Can I use”...
It now exists in CSS4, see this answer.
Otherwise, for jQuery, you can use...
$(':input[name]').filter(function() {
return this.value.toLowerCase() == 'search';
});
jsFiddle.
You could also make a custom selector...
$.expr[':'].valueCaseInsensitive = function(node, stackIndex, properties){
return node.value.toLowerCase() == properties[3];
};
var searchInputs = $(':input:valueCaseInsensitive("Search")');
jsFiddle.
The custom selector is a bit of overkill if doing this once, but if you need to use it many times in your application, it may be a good idea.
Update
Is it possible to have that kind of custom selector for any attribute?
Sure, check out the following example. It's a little convoluted (syntax such as :input[value:toLowerCase="search"] may have been more intuitive), but it works :)
$.expr[':'].attrCaseInsensitive = function(node, stackIndex, properties){
var args = properties[3].split(',').map(function(arg) {
return arg.replace(/^\s*["']|["']\s*$/g, '');
});
return $(node).attr(args[0]).toLowerCase() == args[1];
};
var searchInputs = $('input:attrCaseInsensitive(value, "search")');
jsFiddle.
You could probably use eval() to make that string an array, but I find doing it this way more comfortable (and you won't accidentally execute any code you place in your selector).
Instead, I am splitting the string on , delimiter, and then stripping whitespace, ' and " either side of each array member. Note that a , inside a quote won't be treated literally. There is no reason one should be required literally, but you could always code against this possibility. I'll leave that up to you. :)
I don't think map() has the best browser support, so you can explictly iterate over the args array or augment the Array object.
input[value='Search'] matches
input[value='search' i] Also matches in latest browsers
Support:
version : Chrome >= 49.0, Firefox (Gecko) >= 47.0, Safari >= 9
You can't do it with selectors alone, try:
$('input').filter(function() {
return $(this).attr('value').toLowerCase() == 'search';
});

Want `­` to be always visible

I'm working on a web app and users sometimes paste in things they've copy/pasted from other places and that input may come with the ­ character (0xAD). I don't want to filter it out, I simply need the user to see that there is an invisible character there, so they have no surprises later.
Does anyone know a way to make the ­ always be visible? To show a hyphen, rather than remain hidden? I suspect a custom web font might be needed, if so, does anyone know of a pre-existing one?
You would need to either use JavaScript or a custom typeface that has a visible glyph for the soft-hyphen character. Given the impracticalities of working with typefaces for the web (and burdening the user with an additional hundred-kilobyte download) I think the JavaScript approach is best, like so:
document.addEventListener("DOMContentLoaded", function(domReadyEvent) {
var textBoxes = document.querySelectorAll("input[type=text]");
for(var i=0;i<textBoxes.length;i++) {
textBoxes[i].addEventListener("paste", function(pasteEvent) {
var textBox = pasteEvent.target;
textBox.value = textBox.value.replace( "\xAD", "-" );
} );
}
} );

Strange IE11 form fields bug after selecting from dropdown

I'm experiencing a major bug in IE 11 (latest version 11.0.9600.16521 on Windows 7). When on any form if I open a select dropdown all the other form fields on the page freeze. I can 'unfreeze' them by adjusting the Window size (causing a redraw). This seems to happen on any form what-so-ever.
To reproduce:
Open IE 11.0.9600.16521
Go to http://www.wikipedia.org/
Select any language from the language dropdown
Result:
language dropdown does not appear to get updated on the screen
the search box appears to be frozen - i.e. focus on select box and start typing but no text appears. However if you adjust the window size the form fields are updated and go back to working as normal (until you interact with another select element)
I can't find much in Google for this issue so maybe it's just something specific to my settings. Only thing that sounds somewhat similar to what I'm experiencing is this: http://connect.microsoft.com/IE/feedback/details/806679/ie-11-desktop-selecting-an-item-from-a-drop-down-list-on-a-webpage-causes-the-tab-to-crash. Anyone else able to reproduce this?
I had a similar issue with IE11 that turned out to be any modification to the .text property of an SELECT-option element. I eventually found the "hint" on stackoverflow here
How to fix IE select issue when dynamically changing options.
In my case I use straight JavaScript, and with so many inter-dependent SELECT boxes had to come up with a generic solution, so my solution was to intercept (defineGetter) assignment to any .text property of an HTMLOptionElement, and set a 1 ms timer to perform an add element and remove element as in the referenced post that is titled "I have the fix. We have to add and remove options list to trigger the rendering in IE8." Notice the reference to IE8, AFAIK IE has had several issues with SELECT boxes since at least IE7, possibly earlier.
So the code I added to one of my global scripts is as follows:
try { var IE11; // IE10 and IE11 removed ActiveXObject from the window object but it can still be instantiated
IE11 = new ActiveXObject('MSXML2.DOMDocument.6.0');
IE11 = null;
if (typeof(HTMLOptionElement) != "undefined") {
try { HTMLOptionElement.prototype.__defineSetter__(
'text',
function(original) {
return function(newValue) { var sel;
original.call(this, newValue);
if (!(sel=this.parentElement).fixIE) sel.fixIE = window.setTimeout(_fixIE_(sel), 1);
}
}(HTMLOptionElement.prototype.__lookupSetter__('text')));
} catch(e) {};
}
} catch(e) {}
}
// IE11 broke SELECT boxes again, modifying any options .text attribute "freezes" the SELECT so it appears disabled
function _fixIE_(selBox) {
return _fixIE_;
function _fixIE_(){ var lc = selBox.options.length;
selBox.options.add(new Option('',''));
selBox.options.remove(lc);
selBox.fixIE = undefined;
}
}
Phil
Go to programs
Then widdcom folder
Right click bttray
Go compatibility
Tick run as admin
Restart
I had the same problem in IE 11 on Dell Windows 7.
It was solved by turning off hardware rendering in IE, as you suggested in your link.

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

When a web form is written to the browser, the browsers remembers what the initial values are of a text INPUT box. ie. when it receives HTML like this:
<input type="text" value="something">
The browser remembers "something" as the initial/default value. When the user starts typing over it, then hits ESC, the browser reverts the field to the initial value (or blank if it was initially blank of course).
However, when creating a text input box programatically, hitting ESC always seems to blank the box, even if I create it with a default value like so:
$('<input type="text" value="something">')
The browser doesn't count this as a default value and doesn't revert to it when hitting ESC. So my question is, is there a way to create a text box in code and somehow assign it a default value, so the ESC key works as if the browser received it in the HTML document?
You might looking for the placeholder attribute which will display a grey text in the input field while empty.
From Mozilla Developer Network:
A hint to the user of what can be entered in the control . The
placeholder text must not contain carriage returns or line-feeds. This
attribute applies when the value of the type attribute is text,
search, tel, url or email; otherwise it is ignored.
However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )
And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/
Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/
This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.
var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);
http://jsfiddle.net/gGrf9/
If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.
//store default value for all elements on page. set new default on blur
$('input').each( function() {
$(this).data('default', $(this).val());
$(this).blur( function() { $(this).data('default', $(this).val()); });
});
$('input').keyup( function(e) {
if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});
If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<input type="text" value="default!" id="myInput" />
JavaScript
$(document).ready(function (){
$('#myInput').keyup(function(event) {
// 27 is key code of ESC
if (event.keyCode == 27) {
$('#myInput').val('default!');
// Loose focus on input field
$('#myInput').blur();
}
});
});
Working source can be found here: http://jsfiddle.net/S3N5H/1/
Please let me know if you meant something different, I can adjust the code later.
See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )
btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs