0

I am trying to write a code within a form input such as when the user clicks on the form element (onfocus), the value of the element disappears, but if a user click on any other input element after that (without filling up the previous input element of the form) than the value of the previous element reappears.

The HTML code is shown below:

<label id="color_text">Forename:</label><br />
<input id="f1" class="form-control" type="text" name="forename"    value="Forename" /><br /><br />

The JavaScript i am trying to run is shown below:

<script>
    var new_id = document.getElementById("f1");

    new_id.onfocus = function(){
        if (new_id.value == "Forename"){
        new_id.value = "";
        }
     };

    new_id.onblur = function() {
        if (new_id.value == ""){
        new_id.value = "Forename"; 
        }
    };
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Rahul
  • 27
  • 8

4 Answers4

0

For maximum compatibility you should use addEventListener or attachEvent (whatever is available). So for focus event something like this:

function addEvent(element, evnt, funct){
  if (element.attachEvent)
   return element.attachEvent('on'+evnt, funct);
  else
   return element.addEventListener(evnt, funct, false);
}

addEvent(new_id, 'focus', function() {
  if (new_id.value == "Forename"){
      new_id.value = "";
  }
});

You should read this about events binding. And probably use placeholder in first place, if I am right about what you are trying to accomplish.

Community
  • 1
  • 1
Jan.J
  • 3,050
  • 1
  • 23
  • 33
0

Your code works just fine. http://jsfiddle.net/bigneo/7j217d8y/

I think the problem is your methods are not seen by the document. You could wrap them inside document.ready

Something like this, but requires jQuery:

$(document).ready(function() {
    // your methods here
});
bigneo
  • 141
  • 10
0

Your code works fine in Chrome 44. What's your browser?

And why don't you use placeholder attribute in the <input> label?

Brick Yang
  • 5,388
  • 8
  • 34
  • 45
  • I am using the latest version of Chrome and I know placeholder is an option for me, but that doesn't answer the fact why shouldn't this code work. – Rahul Aug 11 '15 at 13:31
  • I'm sure your code works in Chrome. Did you post all code? Because the code in your post missed the `` end label – Brick Yang Aug 11 '15 at 13:37
0

Your code is fine, you just need to tell the browser when to run it. Wrap it in this:

document.addEventListener('DOMContentLoaded', function() {

    // code goes here

});

This is a much better option for vanilla JS rather than importing the whole JQuery library just to use $(document).ready(function()

Alex Deas
  • 15
  • 5