Tuesday, December 25, 2012

Pre-fill Text Input Box with Grey Text using Javascript

I don't know since when the pre-filled grey text in the text input box becomes so popular. Here's what I do. I hope these are the simplest codes. Enjoy!


The Javascript & HTML:


<script>
function checkText(action) {
  if (document.getElementById('myTextID').value == 'Default Text' && action == 'focus') {
    document.getElementById('myTextID').value = "";
  }
  else if (document.getElementById('myTextID').value == '' && action == 'blur') {
    document.getElementById('myTextID').value = "Default Text";
    document.getElementById('myTextID').style.color = '#bbbbbb';
  }
  else {
    document.getElementById('myTextID').style.color = '#333333';
    // You can put more action here such as the AJAX submit codes
  }
}

</script>

<input type=text name=textName size=20 maxlength=100 id=myTextID onFocus="checkText('focus')" onBlur="checkText('blur')">

<script>
document.getElementById('myTextID').value = 'Default Text';
document.getElementById('myTextID').style.color = '#bbbbbb';
</script>



P.S.: You can change the 'Default Text' to something else.

No comments:

Post a Comment