Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 360
samyb8 Avatar asked Jun 20 '13 16:06

samyb8


3 Answers

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.

like image 194
Dhaval Marthak Avatar answered Oct 24 '22 06:10

Dhaval Marthak


You didn't call the function and you have other errors, should be:

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

Fiddle

You were setting inputVal to the string value of the input, but then you tried to set style.backgroundColor on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.

like image 4
MrCode Avatar answered Oct 24 '22 06:10

MrCode


on body tag's onLoad try setting it like

document.getElementById("subEmail").style.backgroundColor = "yellow";

and after that on change of that input field check if some value is there, or paint it yellow like

function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
    inputVal.style.backgroundColor = "yellow";
            }
    }
like image 4
dev2d Avatar answered Oct 24 '22 04:10

dev2d