简体   繁体   中英

Why this simple JavaScript code not working

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"; 
        }
    };

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.

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
});

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM