Timothy Fisher Timothy Fisher - 2 years ago 173
HTML Question

Javascript: this.value Function Not Working

Ok so I have the following function:

function hideValue(value) {
if (this.value == value) {
this.value = '';

And the following form field:

<input onfocus="hideValue('First Name')" type="text" name="first_name" value="First Name">

I cannot get the function to hide the value. When I
in the function, it returns the correct value.

I also have a showValue function which does the opposite. Why are these not working?

Answer Source

In an event handler on a DOM element this refers to the element only in the first level of the function. Therefore you need to pass this into the function:

  onfocus="hideValue(this,'First Name') /* 'this' is only correct here */"
  type="text" name="first_name" value="First Name"

The function should therefore be modified to:

function hideValue(element, value) {
  if (element.value == value) {
    element.value = '';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download