Я редактировал где-то в вашем коде. Вам не нужно использовать IIFE внутри события change
. Что касается проблемы с цветом фона, вы можете сбросить весь фон на значение по умолчанию, тогда вам просто нужно применить новый фон для текущего элемента, который содержит входные данные.
$(this).closest('.tagboxes').find('input').each(function() {
$(this).closest(".tagbox").css({
"background-color": "#fff",
color: "",
"border-color": ""
});
});
if (this.checked) {
tagbox.css({
"background-color": rgb,
color: contrast,
"border-color": rgb,
color: contrast
});
}
$(document).ready(function() {
function darkness(color) {
color.replace(/^\D+|\)/g, "").trim();
//console.log(color);
var rgb = color.split(",");
//console.log(rgb);
var final =
parseInt(rgb[0], 10) + parseInt(rgb[1], 10) + parseInt(rgb[2], 10);
//console.log(final);
if (final < 384) {
return false;
}
return true;
}
$(".tagboxes").each(function() {
$group = $(this);
$input = $group.find("input");
$input.change(function() {
var label = $(this).next("label");
var tagbox = $(this).closest(".tagbox");
var color = label.data("rgb");
var rgb = `rgb(${color})`;
var contrast = darkness(color) ? "#202124" : "#fdfdfd";
$(this).closest('.tagboxes').find('input').each(function() {
$(this).closest(".tagbox").css({
"background-color": "#fff",
color: "",
"border-color": ""
});
});
if (this.checked) {
tagbox.css({
"background-color": rgb,
color: contrast,
"border-color": rgb,
color: contrast
});
}
});
});
$(function() {
$("#m_clear").on("click", function() {
$("input:checked").each(function() {
$(this).prop("checked", false);
$(this).trigger("change");
});
});
});
});
.tagboxes {
display: flex
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="m_clear">Clear All</button>
<div class="tagboxes">
<div class="tagbox">
<input id="i0" type="radio" name="radio">
<label data-rgb="255,64,129" for="i0">
<b class='text--tagbox'>Lobster</b>
</label>
</div>
<div class="tagbox">
<input id="i1" type="radio" name="radio">
<label data-rgb="49,231,182" for="i1">
<b class='text--tagbox'>Tuna</b>
</label>
</div>
<div class="tagbox">
<input id="i2" type="radio" name="radio">
<label data-rgb="0,0,255" for="i2">
<b class='text--tagbox'>Pine</b>
</label>
</div>
</div>
<div class="tagboxes">
<div class="tagbox">
<input id="x0" type="radio" name="radio2">
<label data-rgb="255,64,129" for="x0">
<b class='text--tagbox'>Lobster</b>
</label>
</div>
<div class="tagbox">
<input id="x1" type="radio" name="radio2">
<label data-rgb="49,231,182" for="x1">
<b class='text--tagbox'>Tuna</b>
</label>
</div>
<div class="tagbox">
<input id="x2" type="radio" name="radio2">
<label data-rgb="0,0,255" for="x2">
<b class='text--tagbox'>Pine</b>
</label>
</div>
</div>