2012-03-16 45 views
3

如何在点击元素或其容器时(取消)检查无线电输入元素?如何在点击时切换无线电输入元素的检查状态?

我曾尝试下面的代码,但它不会取消收音机。

HTML:

<div class="is"> 
    <label><input type="radio" name="check" class="il-radio" /> Is </label> 
    <img src="picture" /> 
</div> 

的jQuery:

$(".is label, .is ").click(function() { 
    if (!$(this).find(".il-radio").attr("checked")) { 
     $(this).find(".il-radio").attr("checked", "checked"); 
    } else if ($(this).find(".il-radio").attr("checked") == "checked") { 
     $(this).find(".il-radio").removeAttr("checked"); 
    } 
}); 
+1

你为什么不只是使用标签在其原来的形式? http://www.w3schools.com/tags/tag_label.asp – 2012-03-16 13:27:47

+2

@OriesokVlassky:因为这需要每个输入控件都有一个ID,以便标签引用它。 ''是有效的HTML;它应该工作。 – cHao 2012-03-16 13:31:35

+0

检查http://stackoverflow.com/questions/2117538/jquery-how-to-uncheck-a-radio-button – 2012-03-16 14:04:09

回答

6

Y你必须防止默认行为。目前发生以下情况:

  1. click容器事件火灾(div.is)。
  2. click事件触发标签。
  3. 由于你的函数切换状态,并且事件监听器被调用了两次,结果是没有任何事情发生。

修正码(http://jsfiddle.net/nHvsf/3/):

$(".is").click(function(event) { 
    var radio_selector = 'input[type="radio"]', 
     $radio; 

    // Ignore the event when the radio input is clicked. 
    if (!$(event.target).is(radio_selector)) { 
     $radio = $(this).find(radio_selector); 
     // Prevent the event to be triggered 
     // on another element, for the same click 
     event.stopImmediatePropagation(); 
     // We manually check the box, so prevent default 
     event.preventDefault(); 
     $radio.prop('checked', !$radio.is(':checked')); 
    } 
}); 
$(".il-radio").on('change click', function(event) { 
    // The change event only fires when the checkbox state changes 
    // The click event always fires 

    // When the radio is already checked, this event will fire only once, 
    // resulting in an unchecked checkbox. 
    // When the radio is not checked already, this event fires twice 
    // so that the state does not change 
    this.checked = !this.checked; 
}); 
+0

你可以做到这一点,如果我点击收音机它自己也会检查它吗? – funerr 2012-03-20 16:21:49

+0

现在图片不会触发选择。 – funerr 2012-03-20 17:26:35

+0

@ agam360此前,'event.target'属性被用作参考。这是错误的,现在已经修复了。 – 2012-03-20 17:34:46

5

单选按钮不取消,你需要使用一个复选框(类型= '复选框')

+0

你能给我正确的方式为无线电这样做呢? – funerr 2012-03-16 13:28:34

+2

单选按钮通常只有在单击具有相同“名称”属性的另一个单选按钮时才会被取消选中,这是基本的HTML – CKKiller 2012-03-16 13:30:19

+0

单选按钮以这种方式工作。如果您想要“取消选中”行为,您应该使用复选框 – MatuDuke 2012-03-16 13:31:11

0

仅使用HTML,相同的功能

<label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio" /> Is </label> 
+0

当控件是标签中唯一的控件时,不需要'for'属性。 – cHao 2012-03-16 13:35:49

+0

但是我想要点击它时自己选择的div ... – funerr 2012-03-16 13:36:12