I would like to know how to implement something like stack overflow when you post a question: "At least one tag such as (css html asp), max 5 tags.
How can I implement something like this for a text input in html, where it is partially faded, but when you type, it doesn't show up, and is not faded.
I don't mind how to do this, as long as it works.
Thanks.
I would like to know how to implement something like stack overflow when you post a question: "At least one tag such as (css html asp), max 5 tags.
How can I implement something like this for a text input in html, where it is partially faded, but when you type, it doesn't show up, and is not faded.
I don't mind how to do this, as long as it works.
Thanks.
Share Improve this question asked Nov 12, 2011 at 17:08 H BellamyH Bellamy 22.7k25 gold badges80 silver badges119 bronze badges4 Answers
Reset to default 7The easiest option is to use the placeholder
attribute:
<input type="text" placeholder="At least one tag, such as 'html', 'asp', max five tags." />
JS Fiddle demo.
If cross-patibility is a requirement, then JavaScript is also an option:
var inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++){
if (inputs[i].hasAttribute('data-hint')){
inputs[i].value = inputs[i].getAttribute('data-hint');
inputs[i].style.color = '#999';
inputs[i].onclick = function(){
this.value = '';
};
inputs[i].onblur = function(){
if (this.value == '' || this.value == this.getAttribute('data-hint')){
this.value = this.getAttribute('data-hint');
this.style.color = '#000';
}
};
}
}
JS Fiddle demo.
Or, with jQuery:
$('input:text').each(
function(){
$(this).val($(this).attr('data-hint'));
$(this).css('color','#999');
}).click(
function(){
$(this).val('');
$(this).css('color','#000');
}).blur(
function(){
if ($(this).val() == ''){
$(this).val($(this).attr('data-hint'));
$(this).css('color','#999');
}
});
JS Fiddle demo.
References:
- Common Input Element Attributes (W3).
Vanilla JavaScript:
document.getElementsByTagName()
.element.onblur
.element.onfocus
.element.hasAttribute()
.element.getAttribute()
.element.style
.
jQuery:
- text-input (
:text
) selector. .each()
..val()
..css()
..attr()
.
<input type="text" name="booga" placeholder="This is default text" />
<input type="text" placeholder="Your text here" />
Requires up-to-date browser, but doesn't use any code of any kind.
<input type="text" placeholder="Default text goes here..."/>
As @Kolink's answer explains, doing this requires an up-to-date browser, but doesn't use code at all.