I have searched for several hours now trying to implent scripts to change the div background. I've found this solution which works when it's not in a loop:
Javascript: onClick checkbox change div color
The challenge here is that the checkboxes is in a foreach loop with unique id values.
Here is my code:
<script language="JavaScript" type="text/JavaScript">
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#0000FF';
} else {
x.style.backgroundColor = '#FF0000';
}
}
</script>
<style type="text/css">
#result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
</style>
</head>
<body>
<?php
$SL = 0;
foreach($results_resultat as $key => $row_resultat) { ?>
<div id="result">
<input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(result, this)">
</div>
<?php } ?>
With this code it will show all the rows which are selected from the tabel but it won't change the div color when clicking the checkbox.
Help is very much appreciated. :-)
You're using the same id result
to wrap all your checkbox elements. id
s should be unique, use class="result"
instead to wrap your checkbox elements. Plus, you don't have to send anything except this
to myFunction
function. So change your code in the following way,
CSS
.result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
PHP
<?php
$SL = 0;
foreach($results_resultat as $key => $row_resultat) { ?>
<div class="result">
<input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(this)">
</div>
<?php
}
?>
JavaScript
function myFunction(_this) {
if (_this.checked) {
_this.parentElement.style.backgroundColor = '#0000FF';
} else {
_this.parentElement.style.backgroundColor = '#FF0000';
}
}
The problem with your code is that line: onChange="myFunction(result, this)"
. At that line result is not defined, usually it is common to pass a string with selector, or string with an id. Something like that onChange="myFunction('result', this)"
And then in you JS
function use document.getElementById
to get a reference to the DOM element.
<script language="JavaScript" type="text/JavaScript">
function myFunction(id, _this) {
if (_this.checked) {
document.getElementById(id).style.backgroundColor = '#0000FF';
} else {
document.getElementById(id).style.backgroundColor = '#FF0000';
}
}
</script>