Link to home
Create AccountLog in
Avatar of earwig75
earwig75

asked on

Toggle input box background color

I'd like to have a couple text fields that are one color until I check a box. I'd like them to toggle from the first color to the 2nd and back depending if the box is checked or not. Below is what I am using but it doesn't seem to work. Could someone assist?

<script type="text/javascript">

function bg1(){
	document.getElementById("div_ID").style.cssText="background-color:#6699FF;";
	}
function bg2(){
	document.getElementById("div_ID").style.cssText="background-color:#ffffff;";
	}	
function BG (it, box) {
	var vis = (box.checked) ? bg1() : bg2();
	return vis;
}
</script>

</head>

<body>
 <input name="CH>" type="checkbox"  onClick="BG('DIV_id', this);" value=""  />
<input type="text" id="div_ID"></input>

Open in new window

Avatar of Tom Beck
Tom Beck
Flag of United States of America image

I think this is what you want.

function bg1(){
      document.getElementById("div_ID").style.backgroundColor="#6699FF";
      }
function bg2(){
      document.getElementById("div_ID").style.backgroundColor="#ffffff";
      }      
function BG (box) {
      var vis = (box.checked) ? bg1() : bg2();
      return vis;
}

<input name="CH>" type="checkbox"  onClick="BG(this);" value=""  />
<input type="text" id="div_ID"></input>

But using cssText did work in my test.
Avatar of earwig75
earwig75

ASKER

I am having a problem with adding more than 1 text box. I should have mentioned that.I would like this to work on 2 or 3 input boxes.
Okay, in that case something like this will work:

function bg1(ele){
      document.getElementById(ele).style.backgroundColor="#6699FF";
      }
function bg2(ele){
      document.getElementById(ele).style.backgroundColor="#ffffff";
      }      
function BG (div, box) {
      var vis = (box.checked) ? bg1(div) : bg2(div);
      return vis;
}

<input name="CH>" type="checkbox"  onClick="BG('div1_ID',this);" value=""  />
<input type="text" id="div1_ID"></input>
<br />
<input name="CH>" type="checkbox"  onClick="BG('div2_ID',this);" value=""  />
<input type="text" id="div2_ID"></input>
I'm sorry - I more question. I'd like it initialize with one of the 2 colors...(brown). When I add the style to the text box it loads white no color.

I want 1 checkbox to control multiple text fields.

Thanks again.
ASKER CERTIFIED SOLUTION
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer