Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  25] [ 5]  / answers: 1 / hits: 22483  / 12 Years ago, mon, november 5, 2012, 12:00:00

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:



JavaScript:



(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 = '' })
})();


HTML



<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!!!


More From » search

 Answers
51

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.


[#82201] Friday, November 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;