A text field in html form have a default value, but I would like to show the placeholder instead of the default value. any ideas?
-
Place holders (Either the HTML5 version or scripted extensions) are visible when the input control has no value.– Mike ChristensenJul 23, 2013 at 2:00
-
field will always have a value, assigning a value when creating the text field - its an edit form.– PeterJul 23, 2013 at 2:16
4 Answers
From what you said here it sounds like you actually want to listen for the focus and blur events and just clear the contents of the <input>
with some kind of cache to restore it if nothing gets typed.
<input id="foo" type="text" value="" data-value="" />
Then in script
var foo = document.getElementById('foo');
foo.addEventListener('focus', function () {
this.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
Provided you are only concerned with browsers that support HTML5, the following is an option:
<input type="text" name="myText" placeholder="My Placeholder">
<input type="text" name="foo" placeholder="Foo Name"/>
<input type="hidden" name="foo" value="foo"/>
On one hand, it is doable; on the other hand, I'm not sure why you should.
$('input[type="text"]').each(function (i, o) {
var inputBox = $(o),
swapInValue = function () {
inputBox.val(inputBox.data('val'));
},
swapOutValue = function () {
inputBox.data('val', inputBox.val()).val('');
};
inputBox.blur(swapOutValue).focus(swapInValue);
});
-
1doing it because I like the fact that with placeholder user can just start typing the new value. Instead of selecting and deleting the previous value first. Sry I'm OCD like that! let me try your code..– PeterJul 23, 2013 at 2:21
-
Yes, with a placeholder, the user can just start typing a new value. However, you are requesting that the placeholder be forced to show even when the text box already has a value.– BrianJul 23, 2013 at 2:28
-