Question

I'm having problems creating a couple functions to clear an input field onfocus and reset it back to the default text onblur if it's empty. It works fine until you change some of the text and then backspace it out.

My functions are:

function enterField (id, defaultText) {
   if (document.getElementById(id).value == defaultText) {
      document.getElementById(id).setAttribute("value", "");
      document.getElementById(id).style.color = "#000000";
   }
}

function leaveField (id, defaultText) {
   if (document.getElementById(id).value == "" || document.getElementById(id).value == defaultText) {
      document.getElementById(id).setAttribute("value", defaultText);
      document.getElementById(id).style.color = "#dddddd";
  }
}

And my html is:

<table style="width: 464px; margin-right: -7px; margin-left: -7px; table-layout: fixed;" cellpadding="0" cellspacing="8">
    <tr>
        <td class="input"><input id="name" type="text" class="name" size="32" value="Name" onfocus="enterField('name', 'Name');" onblur="leaveField('name', 'Name');"></td>
        <td class="input"><input id="email" type="text" class="name" size="32" value="Email" onfocus="enterField('email', 'Email');" onblur="leaveField('email', 'Email');"></td>
    </tr>
    <tr>
        <td class="input" colspan="2"><textarea id="message" class="message" rows="8" onfocus="enterField('message', 'Message');" onblur="leaveField('message', 'Message');">Message</textarea></td>
    </tr>
    <tr>
        <td style="text-align: right;" colspan="2"><input id="submit" type="submit" class="button" value="Send"></td>
    </tr>
</table>

You can see how it operates at www.ag-designs.ca/index_new.php. Click "Let's Talk" at the bottom.

Was it helpful?

Solution

change

document.getElementById(id).setAttribute("value", defaultText);

to

document.getElementById(id).value = defaultText;

at both occurrences in your functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top