Search code examples
javascripttextinputcolorsbackground

Changing background color of text box input not working when empty


I am having a tough time with this javascript code to change the background color of a text input if the input is empty.

Here is the code:

function checkFilled() {
    var inputVal = document.getElementById("subEmail").value;
    if (inputVal == "") {
        inputVal.style.backgroundColor = "yellow";
                }
        }

Example: http://jsfiddle.net/2Xgfr/

I would expect the textbox to come out yellow at the beginning.


Solution

  • DEMO --> http://jsfiddle.net/2Xgfr/829/

    HTML

    <input type="text" id="subEmail" onchange="checkFilled();">
    

    JavaScript

     function checkFilled() {
        var inputVal = document.getElementById("subEmail");
        if (inputVal.value == "") {
            inputVal.style.backgroundColor = "yellow";
        }
        else{
            inputVal.style.backgroundColor = "";
        }
    }
    
    checkFilled();
    

    Note: You were checking value and setting color to value which is not allowed, that's why it was giving you errors. try like the above.