单击div检查单选按钮

时间:2012-07-21 11:40:09

标签: jquery html css

每当我点击它的父div时,我希望单选按钮检查/取消选中。 单选按钮最初是隐藏的。

我试图通过在div周围包裹<label>来实现这一目标。它有效,但jQ.toggleClass停止工作。

HTML

<div class="big">
This is a div 1
<input id="chb" type="radio" />
</div>

<br/>

<div class="big">
This is a div 2
<input id="chb" type="radio" />
</div>

CSS

.big {

    width:100px;
    height:100px;
    background-color:red;
    cursor:pointer;

}

.hli {

    border:2px solid blue;

}

/*.chb{display:none;}*/

JQ

$('.big').click(function() {
$('.hli').toggleClass('hli');   
$(this).toggleClass('hli');
});
  

JSFIDDLE:http://jsfiddle.net/QqVCu/2/

7 个答案:

答案 0 :(得分:17)

那是怎么回事:http://jsfiddle.net/sgospodarets/QqVCu/5/? 所有必要的 - 在标签中包装输入。然后不需要JavaScipt。

答案 1 :(得分:7)

使用纯HTML / CSS解决方案:

.isHidden {
  display: none; /* hide radio buttons */
}

.label {
  display: inline-block;
  background-color: red;
  width: 120px;
  height: 120px;
  padding: 5px 10px;
}

.radio:checked + .label {   /* target next sibling (+) label */
  background-color: blue;
}
<input id="radio_1" class="radio isHidden" name="radio_a" type="radio">
<label for="radio_1" class="label">1</label>

<input id="radio_2" class="radio isHidden" name="radio_a" type="radio">
<label for="radio_2" class="label">2</label>

答案 2 :(得分:3)

告诉我,如果你想要这个:http://jsfiddle.net/QqVCu/6/

Jquery (已更新)

$('.big').click(function() {
if($(this).find('input[type="radio"]').is(':checked')){
   $(this).find('input[type="radio"]').attr('checked', false);
}
else{
   $(this).find('input[type="radio"]').attr('checked', true);
}
$('.hli').toggleClass('hli');    
$(this).toggleClass('hli');

});

答案 3 :(得分:3)

您可以使用prop()方法,请尝试以下操作:

$('.big').click(function() {
  $('.hli').removeClass('hli');
  $(this).addClass('hli').find('input').prop('checked', true)    
});

DEMO

请注意,ID必须是唯一的,为了正常工作,单选按钮应具有名称属性:

<input id="chb1" type="radio" name="radioGroup"/>
<input id="chb2" type="radio" name="radioGroup"/>

答案 4 :(得分:2)

试试这个:http://jsfiddle.net/ZuXvM/

要选中一个单选按钮,您应该按名称对它们进行分组(为该组中的所有按钮指定相同的名称)

答案 5 :(得分:0)

试试这个:

http://jsfiddle.net/QqVCu/50/

为了绕过jQuery事件冒泡,我使用常规JS来触发click()。

$('.big').click(function () {
    $('.hli').toggleClass('hli');
    $(this).toggleClass('hli');
    var Id = $(this).find('input[type=radio]').attr('id');
    document.getElementById(Id).click();
});

答案 6 :(得分:0)

如果您想使用JQuery,这就是您应该这样做的方式

$('.big').on({
    click: function () {

      $('.hli').toggleClass('hli');
      $(this).toggleClass('hli');

    }
}, 'input[name="chb"]');
相关问题