How to change input value onfocus and onblur (no jquery)
Solution 1
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.
Solution 2
<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=''}" />
Try This without Jquery
Solution 3
Without jQuery:
field.onblur = function() {
if (field.value == '') {
field.value = placeholdertext;
}
};
field.onfocus= function() {
if (field.value == placeholdertext ) {
field.value = '';
}
};
ModernDesigner
Updated on September 13, 2020Comments
-
ModernDesigner over 3 years
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!!!