7.6.06

Clear all inputs value on focus

Clear all inputs value on focus


This small function help you to clear predefined value of all inputs on your website


Code:


function init(){
var inp=document.getElementsByTagName('input');
for(var i=0;i<;inp.length;i++){
if(inp[i].type=='text'){
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].onfocus=function(){
if(this.value==this.getAttribute('rel')){this.value='';}
else{return false;}}
inp[i].onblur=function(){
if(this.value==''){this.value=this.getAttribute('rel');}
else{return false;}}
inp[i].ondblclick=function(){this.value=this.getAttribute('rel')}
}}}
if(document.childNodes){window.onload=init}


You can use any onload event which suite to your needs. I am using this one:


if(document.childNodes){window.onload=init}


, because it will works only when function is supported. It is just small prevention of error in MSIE 4


Example:


Test it on styled working example. To view it in action just give some input focus.


Tested in Firefox 0.7+, IE 5+, Opera 7.23+


Use script and style as you want.

5 Comments:

Anonymous Anonymní said...

Thank you, this works very well. :)

9:46 dop., září 12, 2006 
Blogger Unknown said...

Great hint, but how to apply this to textarea?

4:03 odp., června 09, 2010 
Blogger Mirek Komárek said...

just replace document.getElementsByTagName('input'); by document.getElementsByTagName('textarea');

6:09 odp., června 09, 2010 
Blogger vynnus said...

Great script buddy. I need it to work both with inputs and textarea in the same form. What changes shoud I do?

5:43 dop., června 12, 2010 
Blogger Mirek Komárek said...

I uploaded demo for input+textarea here http://xy.wz.cz/input-plus-textarea.html

6:24 dop., června 13, 2010 

Okomentovat

<< Home