Reputation: 13
I want to give background color to the div when the checkbox from table is checked.
Here is the HTML: (checkbox that will effect the background color of div)
<div id="main">
<div id="1"><input type="checkbox" value="1" name="" ></div>
<div id="1"><input type="checkbox" value="2" name="" ></div>
<div id="1"><input type="checkbox" value="3" name="" ></div>
<div id="1"><input type="checkbox" value="4" name="" ></div>
</div>
(checkbox that is in table)
<table id="main1">
<tr>
<td><input type='checkbox' value="1" ></td>
</tr>
<tr>
<td><input type='checkbox' value="2" ></td>
</tr>
<tr>
<td><input type='checkbox' value="3" ></td>
</tr>
<tr>
<td><input type='checkbox' value="4" ></td>
</tr>
</table>
and the jQuery
(for vice-versa checking of table and div checkboxes)
$(function() {
var checkboxes = $(":checkbox").change(function() {
var value = $(this).val();
checkboxes.filter(function() {
return value == $(this).val()
}).not(this).prop('checked', this.checked);
});
});
(for giving the background color to the div when the checkbox from div is checked)
$("#main input[type='checkbox']").on("change", function() {
var that = this;
// alert(that.value);
$(this).parent().css("background-color", function() {
return that.checked ? "rgb(251, 252, 170, 0.7)" : "";
});
});
Upvotes: 0
Views: 61
Reputation: 13407
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div id="main">
<div id="1"><input type="checkbox" value="1" name="">1</div>
<div id="1"><input type="checkbox" value="2" name="">2</div>
<div id="1"><input type="checkbox" value="3" name="">3</div>
<div id="1"><input type="checkbox" value="4" name="">4</div>
</div>
<table id="main1">
<tr>
<td><input type='checkbox' value="1">t1</td>
</tr>
<tr>
<td><input type='checkbox' value="2">t2</td>
</tr>
<tr>
<td><input type='checkbox' value="3">t3</td>
</tr>
<tr>
<td><input type='checkbox' value="4">t4</td>
</tr>
</table>
<script>
$(function() {
var checkboxes = $(":checkbox").change(function() {
var value = $(this).val();
var that = this;
if ($(this).parent()[0].nodeName !== "TD") {
$(this).parent().css("background-color", function() {
return that.checked ? "rgb(251, 252, 170, 0.7)" : "";
});
}
$("div input[value='" + value + "']").parent().css("background-color", function() {
return that.checked ? "rgb(251, 252, 170, 0.7)" : "";
});
checkboxes.filter(function() {
return value == $(this).val()
}).not(this).prop('checked', this.checked);
});
});
</script>
Upvotes: 1