当取消选中复选框时,将div背景颜色设置为继承

时间:2017-12-07 01:08:32

标签: javascript jquery html css checkbox

我目前在群组中有复选框;我希望能够在选中复选框时设置未选中复选框的颜色。



var name = $("input:checkbox[name='fooby[2][]']:checked").prop('id')
var unique_id = $(this).parent().find('label[for="' + name + '"]').find('div.eachText').attr('id')
var2 = $("input:checkbox[name='fooby[2][]']:checked")
if ($(var2).is(":checked")) {
  $("input:checkbox[name='fooby[2][]']:checked").map(function() {
    document.getElementById(unique_id).style.backgroundColor = 'grey';
  })

} else {
  document.getElementById(unique_id).style.backgroundColor = 'inherit'
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />
<label for="group4">
    <div  id="test1" class="eachText ">
        dTLA
        <div class="l_desc ">
            555 West 5th street, 34th floor<br> 811 W 7th St
        </div>

    </div>
</label>
<input type="checkbox " class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />
<label for="group5 " class="eachText1">
<div id="test2" class="eachText">
  Long Beach
  <div class="l_desc">
    100 W Broadway
  </div>
</div>
</label>
&#13;
&#13;
&#13;

我的目标是能够在选中时将复选框设置为灰色,并在取消选中时继承。

1 个答案:

答案 0 :(得分:1)

无需JavaScript即可使用该标记设置颜色。只需使用CSS检查和兄弟选择器

input[type="checkbox"]:checked + label > div {
   background-color: red;
}
<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />
<label for="group4">
    <div  id="test1" class="eachText ">
        dTLA
        <div class="l_desc ">
            555 West 5th street, 34th floor<br> 811 W 7th St
        </div>

    </div>
</label>
<input type="checkbox" class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />
<label for="group5 " class="eachText1">
<div id="test2" class="eachText">
  Long Beach
  <div class="l_desc">
    100 W Broadway
  </div>
</div>
</label>