chromedude
chromedude

Reputation: 4302

How do you change the background color of an <input> element with javascript

I have a <input> element that I want to change the background color on. The code I am currently using is this (but it is not working):

var allBlanksLoc = document.getElementById('text');
var allBlanks = allBlanksLoc.getElementsByTagName('input');

for(i=0; i<allBlanks.length; i++) {
var currentBlank = allBlanks[i];
var wordNum = blanks[i];
var blankWord = text[wordNum];
var usrAnswer = currentBlank.value;

if (usrAnswer != blankWord) {
currentBlank.style.backgroundColor = "red";
}
}

The third to last line being the most important

Update:

I fixed the camelCase on it but it still does not work. Any ideas of bugs there?

The full code is here: http://jsbin.com/imolo3/edit

Upvotes: 3

Views: 8139

Answers (4)

netadictos
netadictos

Reputation: 7722

So not to repeat the solutions other users gave.

I personally use JQuery (and it's where any javascripter ends, overall for browser compatibility issues), and it would:

$(currentBlank).css("background-color","red");

Upvotes: 0

Tim
Tim

Reputation: 9259

Are you sure that this script is running at the right time? If it runs before the page is fully formed, the appropriate elements might not be present.

Upvotes: 1

Brad Mace
Brad Mace

Reputation: 27886

Case is important. What you need is

document.getElementById('test').style.backgroundColor='red';

However

it would be better to use a css rule and use javascript only to add the class to the element.

CSS Rule

input.invalid {
    background-color: red;
}

Javascript

element.className = 'invalid';

Upvotes: 4

casablanca
casablanca

Reputation: 70701

It should be backgroundColor - notice the capital C, JavaScript is case-sensitive.

Upvotes: 2

Related Questions