Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default text on input

How to set blank default text on input field and clear it when element is active.

like image 627
Jaro Avatar asked Jul 09 '09 09:07

Jaro


1 Answers

In modern browsers, you may set the placeholder attribute on a field to set its default text.

<input type="text" placeholder="Type some text" id="myField" /> 

However, in older browsers, you may use JavaScript to capture the focus and blur events:

var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling     if (elem.addEventListener) elem.addEventListener(type, fn, false);     else if (elem.attachEvent) elem.attachEvent('on' + type, fn); }, textField = document.getElementById('myField'), placeholder = 'Type some text'; // The placeholder text  addEvent(textField, 'focus', function() {     if (this.value === placeholder) this.value = ''; }); addEvent(textField, 'blur', function() {     if (this.value === '') this.value = placeholder; }); 

Demo: http://jsbin.com/utecu

like image 96
moff Avatar answered Oct 11 '22 19:10

moff