I created the following Javascript as input placeholder attribute alternative for browsers that don't support the input placeholder attribute, like old versions of Internet Explorer:
function placeholder_check(value1) {
if(document.getElementById(value1).getAttribute('value') == null || document.getElementById(value1).getAttribute('value') == '') {
document.getElementById(value1).setAttribute('value', '');
}
if(document.createElement('input').placeholder == undefined) {
if(document.getElementById(value1).getAttribute('value') == '') {
document.getElementById(value1).setAttribute('value', document.getElementById(value1).getAttribute('placeholder'));
}
}
}
This code will set the value of an input to the placeholders value. But only, if the placeholder attribute is not supported by the browser. If it is supported, the placeholder attribute will be used instead. This code will also only get executed if the value attribute in not set.
It's easy to implement since you only need a specific id for every input and just a small piece of Javascript to call the function like that: onmouseover="placeholder_check(this.id);"
, e.g.:
<input id="input1" placeholder="plaseholder 1" onmouseover="placeholder_check(this.id);">
I tested this code a little bit and it seems to work. Since I'm not very familiar with Javascript, I'd like to know if I did everything right? Or, is there something I should improve? Or, something unexpected that won't work on some browsers?
For who is interested in it, here's the working code:
<!DOCTYPE html>
<html>
<head>
<script>
function placeholder_check(value1) {
if(document.getElementById(value1).getAttribute('value') == null || document.getElementById(value1).getAttribute('value') == '') {
document.getElementById(value1).setAttribute('value', '');
}
if(document.createElement('input').placeholder !== undefined) {
if(document.getElementById(value1).getAttribute('value') == '') {
document.getElementById(value1).setAttribute('value', document.getElementById(value1).getAttribute('placeholder'));
}
}
}
function placeholder_check_start() {
var elements = document.querySelectorAll("form input");
for (var i = 0, element; element = elements[i++];) {
if(element.id != null && element.id != '') {
placeholder_check(element.id);
}
}
}
</script>
</head>
<body onload="placeholder_check_start();">
<form>
<input id="fff" placeholder="Input 1">
<input id="lll" placeholder="Input 2">
<input id="uuu" placeholder="Input 3">
</form>
</body>
</html>
After page load, this will automatically loop thought all input fields within a form and set the value to the placeholders text, but only if the browser doesn't support input placeholder attribute and is the value isn't set already.