为什么在取消选中单选按钮时jquery无法检测到?

时间:2013-01-15 22:18:39

标签: javascript jquery html

  

可能重复:
  JQuery $(#radioButton).change(…) not firing during de-selection

我有以下HTML / jQuery:

<input id="rb1" type="radio" name="rb" checked="true">
<input id="rb2" type="radio" name="rb">


$("#rb2").change(function () {
    if ($(this).is(":checked")) {
         alert('checked');
    }
    else {
        alert('unchecked');
    }
});

如果通过选择rb1取消选中我的rb2单选按钮,则不会触发更改事件。为什么是这样?是否可以在不更改我的选择器以匹配两个输入然后查看ID的情况下使其正常工作?

小提琴:http://jsfiddle.net/4uRWR/

4 个答案:

答案 0 :(得分:12)

只有在您实际修改项目本身时才会发送更改事件。单击其他收音机时,您不会对其进行修改。修复方法是在每个输入上观察更改事件:radio,然后只检查相关单选按钮的状态:

$("input:radio").change(function () {
if ($("#rb2").is(":checked")) {
             alert('checked');
    }
    else {
        alert('unchecked');
    }
});

http://codepen.io/AlienHoboken/pen/akwjB

答案 1 :(得分:7)

听取与您的无线电组相关的每个输入的更改,然后检查是否选择了特定的一个。

$("input[name=rb]").change(function () {
    if ($('#rb2').is(":checked")) {
        alert('checked');
    } else {
        alert('unchecked');
    }
});

http://jsfiddle.net/4uRWR/2/

答案 2 :(得分:1)

您可以人为地触发来自同一组的单选按钮的“更改”,以便拾取原始绑定处理程序并输出“未选中”。诀窍是避免通过递归重新触发事件而陷入无限循环,我们可以通过忽略缺少originalEvent属性的人为事件来避免这种情况:

$("input[type=radio]").on("change", function (e) {
  var $this = $(this);

  //all inputs with the same name
  var $targetInputSelector = $("input[name=" + $this.attr("name") + "]");

  //check if the handler was fired "naturally"
  //if yes, trigger the change handler "artificially" for inputs with the same name
  if (e.hasOwnProperty('originalEvent')) {
    //exclude the element that was changed "naturally"
    //from the subset of all the elements with the same name
    $targetInputSelector.not($this).triggerHandler("change");
  }
});

此代码在添加到当前处理程序之后工作并满足而不更改我的选择器以匹配两个输入,然后查看ID 条件;)

http://jsfiddle.net/a73tn/24/

答案 3 :(得分:0)

我几天前遇到了这个问题。我没有听单独点击单选按钮,而是单击<ul>我有他们,然后调用此函数来检查是否已经选中了。

// Iterate over the radio group and determine if one of them is selected
function loopRadBtns(btnGroup)
{
    var isChecked = false;

    btnGroup.find('input[type="radio"]').each(function()
    {
        if($(this).attr('checked'))
        {
            isChecked = true;
        }
    });
    return isChecked;
}