当未选择元素时,请取消选中复选框.仅检查一个复选框.更改相关DIV容器的背景色


<div id="grand-parent" class="grand-parent">
        <div class="parent-div">
            <p> A </p>
            <input type="checkbox"  class="select-me" name="1" value="1"/> 
         </div>   
</div>
<div id="grand-parent-1" class="grand-parent">
        <div class="parent-div">
            <p> B </p>
            <input type="checkbox"  class="select-me" name="2" value="2"/> 
    </div>
</div
    ><div id="grand-parent-2" class="grand-parent">
        <div class="parent-div">
            <p> C </p>
            <input type="checkbox"  class="select-me" name="3" value="3"/> 

        </div>   
</div>

$('.select-me').change(function(){
    if($(this).is(':checked'))
    {
        $('.select-me').each(function(){ $(this).attr('checked', false); });
        $(this).attr('checked', true);
        $('#grand-parent').css('background','#999');
    }
    else if($(this).not(':checked')){
        $('.select-me').each(function(){ $(this).attr('checked', false); });
           $(this).attr('checked', false);
        $('.grand-parent').css('background','green');
    }
});

JSFIDDLE http://jsfiddle.net/2xsy5/27/

我需要帮助来更改相关复选框的背景色。一次只能选择一个复选框。所有未选择的复选框都应具有默认的背景色。只有所需的复选框应具有不同的背景色。感谢您的帮助。

您可以尝试一下,希望这是您期望的!

$(function(){
    $('.select-me').change(function(){
        $this = $(this);
        $('.select-me').each(function(){
            if($(this).val()==$this.val())
            {
              $(this).parents('.grand-parent').css('background','#999');
            }else{
                $(this).attr('checked', false);
                $(this).parents('.grand-parent').css('background','green');
            }
        });
    });
});

演示: http://jsfiddle.net/fvn7v/

,我建议使用radio元素一次,如果您只想一次检查一个表单元素。

要解决背景问题,您可以使用更改事件获取输入元素父母:

$('[type=checkbox]').change(function(){
      $('[type=checkbox]').not(this).removeAttr('checked').parents('.grand-parent').removeClass('selected');
    $(this).parents('.grand-parent').addClass('selected');
});

注意:根据要求,更新了将类添加到Grand Parent Div的演示,然后将类删除到未检查的所有输入中。

有很多方法可以将DOM遍历所需的元素,您可以使用.parent().parent()或其他方法,但结果是相同的。

http://jsfiddle.net/2xsy5/31/

相关内容

最新更新