Timothy Fisher Timothy Fisher - 1 year ago 38
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?


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 = '';