如何在点击时选中/取消选中单选按钮?

Ric*_*nop 34 javascript jquery

我希望能够通过单击取消选中一个单选按钮.

因此,如果未选中单选按钮,我想检查它,如果选中它,我想取消选中它.

这不起作用:

$('input[type=radio]:checked').click(function(){
    $(this).attr('checked', false);
});
Run Code Online (Sandbox Code Playgroud)

我现在无法检查单选按钮.

Hex*_*ive 69

不是要替换复选框,而是允许无线电组返回到未选中的状态.这很棘手,因为无线电选择不像正常事件那样.

浏览器处理正常事件链外的单选按钮.因此,使用event.preventDefault()或event.stopPropagation()的radiobutton上的单击处理程序不会阻止检查单选按钮..removeAttr('checked')必须在setTimeout中完成以允许事件完成,并且浏览器检查radiobutton(再次),然后setTimeout将触发.

这也正确地处理了用户启动mousedown但在mouseup之前离开radiobutton的情况.

//$ = jQuery;
$(':radio').mousedown(function(e){
  var $self = $(this);
  if( $self.is(':checked') ){
    var uncheck = function(){
      setTimeout(function(){$self.removeAttr('checked');},0);
    };
    var unbind = function(){
      $self.unbind('mouseup',up);
    };
    var up = function(){
      uncheck();
      unbind();
    };
    $self.bind('mouseup',up);
    $self.one('mouseout', unbind);
  }
});
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助


Ste*_*hen 14

试试这个:

$('input[type=radio]').click(function(){
    if (this.previous) {
        this.checked = false;
    }
    this.previous = this.checked;
});
Run Code Online (Sandbox Code Playgroud)

  • 由于@HexInteractive在回答中说明的原因,您的解决方案效果不佳.我在Webkit中,它表现得非常不稳定......是的,它允许取消选择一个单选按钮,但大多数时候你必须单击单选按钮两次才能让它们选择.http://jsfiddle.net/sparky672/KdZG7/ (6认同)

小智 8

接受的答案不适用于移动设备.它依赖于与鼠标事件相关的setTimeout和绑定,这些事件不会在平板电脑/移动设备上触发.
我的解决方案是使用"click"事件处理程序和自定义类状态手动跟踪选定的状态.

  1. 处理无线电输入元素上的点击事件
  2. 检查单击元素上是否存在"selected"类
  3. 如果确实如此,(意味着它之前被点击过),删除该类并取消选中该元素,返回
  4. 如果没有,则从同名的所有元素中删除该类,并将其仅添加到单击的元素中.

无需阻止默认行为.这是Jquery中的代码:

$("input:radio").on("click",function (e) {
    var inp=$(this); //cache the selector
    if (inp.is(".theone")) { //see if it has the selected class
        inp.prop("checked",false).removeClass("theone");
        return;
    }
    $("input:radio[name='"+inp.prop("name")+"'].theone").removeClass("theone");
    inp.addClass("theone");
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/bhzako65/


gma*_*man 5

我一定很想念它,但经过这么多年,AFAIK 上面的解决方案似乎都不起作用,或者我可能只是愚蠢。

除非在同一组中有多个单选按钮,否则绝对没有理由使用单选按钮。如果它是一个单独的单选按钮,那么只需使用一个复选框。使用单选按钮的原因是为了选择互斥选项之一。这意味着任何只查看单个按钮的解决方案都将失败,因为单击一个按钮会影响其他按钮的状态

换句话说,由于我们使用的是radioboxes,因此解决方案需要为

<input type="radio" name="foo" id="foo1"><label for="foo1">foo1</label>
<input type="radio" name="foo" id="foo2"><label for="foo2">foo2</label>
<input type="radio" name="foo" id="foo3"><label for="foo3">foo3</label>
Run Code Online (Sandbox Code Playgroud)

这是查看所有按钮的一个。

这似乎有效

<input type="radio" name="foo" id="foo1"><label for="foo1">foo1</label>
<input type="radio" name="foo" id="foo2"><label for="foo2">foo2</label>
<input type="radio" name="foo" id="foo3"><label for="foo3">foo3</label>
Run Code Online (Sandbox Code Playgroud)
document.querySelectorAll(
    'input[type=radio][name=foo]').forEach((elem) => {
  elem.addEventListener('click', allowUncheck);
  // only needed if elem can be pre-checked
  elem.previous = elem.checked;
});

function allowUncheck(e) {
  if (this.previous) {
    this.checked = false;
  }
  // need to update previous on all elements of this group
  // (either that or store the id of the checked element)
  document.querySelectorAll(
      `input[type=radio][name=${this.name}]`).forEach((elem) => {
    elem.previous = elem.checked;
  });
}
Run Code Online (Sandbox Code Playgroud)
body { font-size: xx-large; }
label, input {
  /* added because a second click to unselect radio often
     appears as a double click to select text */
  -webkit-user-select: none;
  user-select: none;
}
Run Code Online (Sandbox Code Playgroud)

请注意是否elem.previous担心您可以使用elem.dataset.previous

另一种解决方案是存储选中的按钮

<input type="radio" name="foo" id="foo1"><label for="foo1">foo1</label>
<input type="radio" name="foo" id="foo2"><label for="foo2">foo2</label>
<input type="radio" name="foo" id="foo3"><label for="foo3">foo3</label>
Run Code Online (Sandbox Code Playgroud)
function makeRadioboxGroupUnCheckable(groupSelector) {

  let currentId;

  document.querySelectorAll(groupSelector).forEach((elem) => {
    elem.addEventListener('click', allowUncheck);
    // only needed if can be pre-checked
    if (elem.checked) {
      currentId = elem.id;
    }
  });

  function allowUncheck(e) {
    if (this.id === currentId) {
      this.checked = false;
      currentId = undefined;
    } else {
      currentId = this.id;
    }
  }
}

makeRadioboxGroupUnCheckable('input[type=radio][name=foo]');
Run Code Online (Sandbox Code Playgroud)
body { font-size: xx-large; }
label, input {
  /* added because a second click to unselect radio often
     appears as a double click to select text */
  -webkit-user-select: none;
  user-select: none;
}
Run Code Online (Sandbox Code Playgroud)