如何在点击时切换无线电输入元素的检查状态?

fun*_*err 4 javascript jquery radio-button

单击元素或其容器时如何(取消)检查无线电输入元素?

我已经尝试了下面的代码,但它没有取消选中收音机.

HTML:

<div class="is">
    <label><input type="radio" name="check" class="il-radio" /> Is </label>
    <img src="picture" />
</div>
Run Code Online (Sandbox Code Playgroud)

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");
    }
});
Run Code Online (Sandbox Code Playgroud)

CKK*_*ler 6

单选按钮不取消选中,您需要使用复选框(type ='复选框')

  • 如果使用相同的"名称"属性单击另一个单选按钮,则通常仅取消选中单选按钮,它是基本HTML (2认同)

Rob*_*b W 6

您必须阻止默认行为.目前,点击后,会发生以下情况:

  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;
});
Run Code Online (Sandbox Code Playgroud)