获取单选按钮之前的状态单击事件/取消选中之前检查过的收音机

时间:2015-06-23 06:04:39

标签: javascript jquery html radio

如何查看click事件中是否已选中单选按钮?

实际上我想做的是,如果先前点击了点击的广播,并且用户再次点击相同的广播,则取消选中它。

但是下面的代码总是评估if条件为真:P

$('input.radiooption').click(function(g) {
    if ($(this).is(":checked")) {
        console.log("already checked, now uncheck it");
    } else {
        console.log("Not checked");
    }
});

P.S。

事情是, 当我点击未选中的单选按钮时,它会被检查

当我点击已经选中的按钮时,会检查

所以,我想知道一种方法来确定click事件中单选按钮的先前状态。

JS FIDDLE

2 个答案:

答案 0 :(得分:2)

使用临时变量跟踪以前的状态:



var prv;
var markIt = function(e) {
  if (prv === this && this.checked) {
    this.checked = false;
    prv = null; //allow seemless selection for the same radio
  } else {
    prv = this;
  }
};
$(function() {
  $('input.radiooption').on('click', markIt);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你走了:

var makeRadiosDeselectableByName = function(name){
    $('input[name=' + name + ']').click(function() {
        if($(this).attr('previousValue') == 'true'){
            $(this).attr('checked', false)
        } else {
            $('input[name=' + name + ']').attr('previousValue', false);
        }

        $(this).attr('previousValue', $(this).attr('checked'));
    });
};

以下是完整示例:http://jsfiddle.net/EtNXP/1467/

相关问题