简体   繁体   中英

How to change input value onfocus and onblur (no jquery)

I wrote some code, kind of like an alternative for HTML5 placeholder using JavaScript, but it's not working. As far as I can figure (with my mediocre knowledge of js), everything should work, but it's not. Please help!!! Here's my code:

(function(){
    var field = document.getElementById('placeholder');
    var placeholdertext = "Search box"; // << change this to whatever you want the placeholder text to be

    field.setAttribute("onblur", "if(value=='') { value = '" + placeholdertext + "'")
    field.setAttribute("onfocus", "if(value=='" + placeholdertext + "') { value = '' }")
})(); 

<input type="search" value="Search box" id="placeholder">

Edit:

I don't want to use jQuery or inline-html-coding, please. Thanks for any help, guys!!!

Replace value with this.value in your code (as you need to check the value of the element that triggers an event, and not some global variable) and it will work .

As a sidenote, perhaps I'd prefer still using placeholder attribute here, providing a JS shim only for the browsers that don't support it. This would simplify the javascript code part too, as you wouldn't have to use some variable just to store some DOM-related data:

field.onblur = function() {
  if (this.value === '') {
    this.value = this.getAttribute('placeholder');
  }
};

field.onfocus = function() {
  if (this.value === this.getAttribute('placeholder') ) {
    this.value = '';
  }
};

... and in fact I'd prefer using addEventListener/attachEvent here instead of onblur/onfocus , as described in this answer .

Without jQuery:

field.onblur = function() {
  if (field.value == '') {
    field.value = placeholdertext;
  }
};

field.onfocus= function() {
  if (field.value == placeholdertext ) {
    field.value = '';
  }
};
<input type="text" value="Enter The User Name" onblur="if(this.value == '') { this.style.color='#f00'; this.value='Enter The User Name'}" onfocus="if (this.value == 'Enter The User Name') {this.style.color='#000'; this.value=''}" />

试试这个没有jQuery的

I haven't tested this but if i'm understanding your question this should work. If it works don't forget to hit the check mark.

    var field = document.getElementById('placeholder');
    var placeholdertext = "Search box";

    field.bind('onblur', function() {
        if (field.text() === '') {
            field.text(placeholdertext);
        }
    });

    field.bind('onfocus', function() {
        if (field.text() === '') {
            field.text(placeholdertext);
        }
    });

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