0

I'm trying o change the background color of a div if a checkbox is checked.

It's working for the div outside the loop, but not for the ones inside. All the variables appear fine, so i think is a syntax error.

Thanks!

<input type="checkbox" name="check0" value='1' <?php echo ((${executed_mod0}=="1")? "checked" : ''); ?> onchange='this.nextSibling.style.backgroundColor = this.checked ? "#6EDBFF" : "white";'><input type="text" name="procedure0" value="<?php echo $repair_mod0;?>">

<?php   
$i=1;
while($i<$nrpm)
{
echo '<br><input type="checkbox" name="check'.$i.'" value="1"'. ((${executed_mod.$i}=="1")? "checked":"").' onchange="this.nextSibling.style.backgroundColor = this.checked ? \"#6EDBFF\" : \"white\";"><input type="text" name="procedure'.$i.'" value="'.${repair_mod.$i}.'">';
$i++;
};
?>
5
  • 1
    why did you tag javascript? looks like PHP!? Commented Nov 21, 2015 at 13:56
  • 1
    Here's a jQuery solution jsfiddle.net/gabrieleromanato/dHZS9 Commented Nov 21, 2015 at 14:00
  • Possible duplicate of How to change the checked mark color of a checkbox in HTML? Commented Nov 21, 2015 at 14:06
  • @caramba It's javascipt and php. I had to tag also php, but my main problem here is with Javascipt... Thanks Commented Nov 22, 2015 at 8:04
  • @AmitSingh You have a +1 for jQuery but i solved it with Javascipt Commented Nov 22, 2015 at 8:05

1 Answer 1

2

Maybe this can get you in the right direction. I added one more .nextSibling when getting the textbox to set background color for.

HTML

<input type="checkbox" name="check0" value='1' onchange='setColor(this)' />
<input type="text" name="procedure0" value="1" />

<input type="checkbox" name="check1" value='2' onchange='setColor(this)' />
<input type="text" name="procedure1" value="2" />

<input type="checkbox" name="check2" value='3' onchange='setColor(this)' />
<input type="text" name="procedure2" value="3" />

JavaScript

function setColor(ele){
    ele.nextSibling.nextSibling.style.backgroundColor = ele.checked ? "#6EDBFF" : "white";   
}
Sign up to request clarification or add additional context in comments.

3 Comments

@ Arg0n Thanks! It's not working with nextSibling.nextSibling but it's working having the function out of php. I'm just scratching the surface in Javascipt and i didn't know you can't have javascipt inside php... Or you can?
I'm not really familiar with PHP, but i suppose if the generated HTML/JS looks ok it should work.
@chioiu daniel Btw, you may want to test your code in Chrome, since i had to add one nextSibling to get it working. If it does not work, you might want to restructure your HTML and change the selector for the textbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.