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!!!
Replace
valuewiththis.valuein 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
placeholderattribute 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:… and in fact I’d prefer using
addEventListener/attachEventhere instead ofonblur/onfocus, as described in this answer.