Search code examples
javascripthtmldrop-down-menuonfocusdropdownbox

Shade Color of Dropdown and Select on focus/onblur


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

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