Shade Color of Dropdown and Select on focus/onblur
-
07-07-2021 - |
Question
How can the code below be modified such that it will apply the onblur
and onfocus
to the text boxes and select boxes? Right now it only works with text boxes, and I can't seem to get it to apply to the select boxes.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload =
function fnOnLoad() {
var t = document.getElementsByTagName('INPUT');
var i;
for(i=0;i<t.length;i++)
{
//alert(t[i].type)
if(t[i].type == "text")
{
t[i].attachEvent('onfocus', new Function("fnTXTFocus('"+t[i].id+ "')"));
t[i].attachEvent('onblur', new Function("fnTXTLostFocus('"+t[i].id+ "')"));
}
}
}
function fnTXTFocus(varname) {
var objTXT = document.getElementById(varname)
objTXT.style.backgroundColor = "#FFFF80";
}
function fnTXTLostFocus(varname)
{
var objTXT = document.getElementById(varname)
objTXT.style.backgroundColor = "#FFFFFF";
}
</script>
</head>
<body>
<input id="t1" type="text" >
<input id="t2" type="text" >
<input id="t3" type="text" >
<br><br>
<select size="d1" ></select>
<select size="d2" ></select>
<select size="d3" ></select>
<p>When the input field gets focus,
a function is triggered which changes the background-color.</p>
</body>
</html>
Solution 3
<script type="text/javascript">
function fnOnLoad() {
var t = document.getElementsByTagName('INPUT');
for (var i = 0; i < t.length; i++) {
t[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4';};
t[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
var d = document.getElementsByTagName('SELECT');
for (var i = 0; i < d.length; i++) {
d[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
d[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
}
</script>
OTHER TIPS
So what you need to do is also get all selects and attach the event handlers to them:
var s = document.getElementsByTagName('SELECT');
Try this:
function fnOnLoad() {
var inputs = document.getElementsByTagName('INPUT');
for(var i = 0; i < inputs.length; i++)
{
inputs[i].attachEvent('onfocus', function(){
this.style.backgroundColor = "#FFFF80";
});
inputs[i].attachEvent('onblur', function(){
this.style.backgroundColor = "#FFFFFF";
});
}
var selects = document.getElementsByTagName('SELECT');
for(var i = 0; i < selects.length; i++)
{
selects[i].attachEvent('onfocus', function(){
this.style.backgroundColor = "#FFFF80";
});
selects[i].attachEvent('onblur', function(){
this.style.backgroundColor = "#FFFFFF";
});
}
}
window.onload = fnOnLoad;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow