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

ingredient_15939 picture ingredient_15939 · Jan 20, 2012 · Viewed 177k times · Source

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?

Answer

nuala picture nuala · Nov 30, 2012

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/