onClick() clear text field

I have a form like this:

<form name=“subscribe” class=“subscribe-form” method=“post”>

<input type=“text” name=“txtEmail” style=“border:0px;” id=“email” value=“Email” /><br>

<input type=“password” style=“border:none” name=“txtPwd” value=“Password” />   
<input type=“submit” name=‘btnSubscribe’ class=“submit button1” value=“” />
</form>

I want that when a user clicks in the textfields, it should be cleared, so that the user can write their own email and password.
But if they leave it empty, then the previous texts should cone in again…

I am doing this bcoz I m not placing captions with the fields.

This should work:

(Put above </body>)


<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for( var i = 0 ; i < inputs.length ; i++ ) {
 if(inputs[i].type=="text"||inputs[i].type=="password") {
  inputs[i].onfocus = function() {
   if(this.value==this.defaultValue) this.value = '';
  }
  inputs[i].onblur = function() { 
   if(this.value=='') this.value = this.defaultValue;
  }
 }
}
</script>

Its good… But I have more than one forms on my page. And I want to implement it on one of those… the one I posted in my above post…

Could it be done…!

The script I gave you should work with ALL inputs on the page (types - “password” and “text”) … :slight_smile:

If you need to target a specific form within the page then add “getElementById(“FORM_ID”)” just before “getElementsByTagName(“input”)”…

So that first line should now look like this:


var inputs = document.getElementById("FORM_ID").getElementsByTagName("input");

Replace FORM_ID with the actual ID of the form you want to target.

Make sure that you put the script at the bottom of the page (above the </body>) - i.e. ABOVE THE END BODY TAG…

If you have to put it in the <HEAD> section then simply put it inside an ONLOAD function like so:


window.onload = function() {
    // PUT THE SCRIPT HERE
}

Be aware though that when you place scripts inside the onload event, it may take a while for them to activate, especially if someone is using a modem.