在收音机选择时更改背景颜色

时间:2009-10-04 15:50:06

标签: jquery css background radio-button

我有以下代码

 <form id="form1" name="form1" method="post">
     <table width="100%" border="0" cellspacing="0" cellpadding="0">

  <tr>
      <td ><div class="label_main" id="lab1">
        <div class="label_radio">
          <input type="radio" name="group1" id="r0" value="0" />
        </div>
        <div class="label_top">
          <label for="r0">Group1</label>
        </div>
        <div class="label_desc">
          <label for="r1">Members of Groups1 </label>
        </div>
      </div>
          </div>    </tr>
    <tr>
      <td><div class="label_main">
        <div class="label_radio">
          <input type="radio" name="group1" id="r1" value="1" />
        </div>
        <div class="label_top">
          <label for="r1">Groups2</label>
        </div>
        <div class="label_desc">
          <label for="r1">Only Group 2 </label>
        </div>
      </div></td>
    </tr>
</table>
</form>



.label_main_selected
    {
    padding-top:0px;
    float:left;
    background:#E9ECFF;
    }

我想要的是:

一旦我选择任何单选按钮,主DIV的背景就会改变,如(label_main_selected)class

由于

3 个答案:

答案 0 :(得分:1)

漫长的道路:

$('input:radio').click(function() {
    if($(this).is(':checked')) {

        //select the main div wrapping this radio
        $(this).parent().parent().addClass('.label_main_selected');

        //or you can do
        //$(this).closest('.label_main').addClass('.label_main_selected');
    } else {
        $(this).parent().parent().removeClass('.label_main_selected');
        //or $(this).closest('.label_main').removeClass('.label_main_selected');
    }
});

简短的方法(可能适合或不适合此目的,取决于完全你所追求的目标):

$('input:radio').click(function() {
    $(this).parent().parent().toggleClass('.label_main_selected');
    //or $(this).closest('.label_main').toggleClass('.label_main_selected');
});

请参阅:

答案 1 :(得分:0)

$(document).ready(function(){
    $("input:radio").click(function(){
       if ($(this).is(":checked")){
       $("label").css({"color":"green","background-color":"#6600cc"}) && $(this).closest("label").css({"color":"green","background-color":"orange"});
       }
    });
});
input[type=radio],
     input[type=checkbox] {
       display: none;
     }
label {
color:white;
font-size:48px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form>
  <label for="Male">
    <input type="radio" class="button" id="Male" name="gender">Male
  </label>
  <label for="Female">
    <input type="radio" class="button" id="Female" name="gender">Female
   </label>
</form>

答案 2 :(得分:0)

$('input:radio').click(function() {
    var selected = $(this).val();
    $(".checkboxtable").find("tr").each(function() {
        var idx = $(this).data("id");
        if(idx == selected){
            $("#dspackage-"+idx).addClass("bg");    
        }else{
            $("#dspackage-"+idx).removeClass("bg");    
        }
    });
});