1

I have checked with an alert, my value is "Enter your comment...", but my if statement returns false.

Thank you.

function ClearText(e) {

  //alert(document.getElementById('contactMe').value);
  if (document.getElementById('contactMe').value == 'Enter your comment...') {
    document.getElementById('contactMe').value = "";
  }

}


var x = document.getElementById('contactMe');
x.addEventListener('click', ClearText, false);
<html>

<body>
  <textarea id=contactMe rows=4 cols=40>Enter your comment...</textarea>
  <script src="contactBox.js">
  </script>
</body>

</html>

3 Answers3

1

I see what you are trying to accomplish and you can avoid the all together by using the html attribute placeholder.

Consider the following code.

<html>

<body>
  <textarea id=contactMe rows=4 cols=40 placeholder='Enter your comment...'></textarea>
  <script src="contactBox.js">
  </script>
</body>

</html>
Jesse
  • 2,790
  • 1
  • 20
  • 36
0

You can do it too as follows:

function clearText(field){
 if(field.defaultValue == field.value){
  field.value = "";
 }
 else if(field.value == ""){
  field.value = field.defaultValue;
 }
}
<html>

<body>
  <textarea id=contactMe rows=4 cols=40 onfocus="clearText(this);" onblur="clearText(this);">Enter your comment...</textarea>
</body>

</html>
Osmani
  • 300
  • 2
  • 16
-1

You can use the placeholder attribute to do this

<html>

<body>
  <textarea id="contactMe" rows="4" cols="40" placeholder="Enter your comment..."></textarea>
  <script src="contactBox.js">
  </script>
</body>

</html>

Be informed that this is not supported in IE8 and you have to use javascript for that

My favourite plugin to do this is Mathias. Go for it if you need to support IE8. Also you have not used double quotes in your html for attributes (id="contactMe"). (though it will work without it, it is recommended by w3 to use quotes)

If you need a full jQuery solution you can use the below code. Here is the fiddle

var placeholderText = "Enter your comment...";

$(document).on("click","#contactMe",function(e){
 if($(this).val()=="" ||$(this).val() == placeholderText ){
  $(this).val("");
}
});

$(document).on("focusout","#contactMe",function(e){

    if($(this).val()==""){
      $(this).val(placeholderText);
    }

});

$(document).ready(function(){
 $("#contactMe").val(placeholderText);
});
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150