单击时取消选中单选按钮

Mar*_*yzs 1 html javascript jquery radio-button

我正试图通过点击jquery取消选择一个单选按钮.

通缉行为:

  1. 如果已单击单击单选按钮,则取消选中
  2. 如果未单击单击单选按钮,请选中

这是我的小提琴:http://jsfiddle.net/2te28/15/

和我的代码:

$('.table').on('click mousedown', '.radio', function() {
    if($(this).attr('id') == $(this).parents('tr').find('.radio:checked').attr('id'))
        $(this).removeAttr('checked');
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,无论我点击什么,总是取消选中.
编辑:更正了id转录错误
EDIT2:两个单选按钮无法同时被选中!

the*_*dox 6

更改您的HTML.你已经改变了id,但你也要改变name.

HTML

$('.table').on('click', '.radio', function() {
  if (this.getAttribute('checked')) { // check the presence of checked attr
    $(this).removeAttr('checked'); // if present remove that
  } else {
    $(this).attr('checked', true); // if not then make checked
  }
});
Run Code Online (Sandbox Code Playgroud)

jQuery的

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <tr>
    <td>
      <input type="radio" id="radio1" name="1" checked="checked" class="radio" />
      <input type="radio" id="radio2" name="2" checked="checked" class="radio" />
    </td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

DEMO

根据评论

$('.table').on('click', '.radio', function() {
  if (this.getAttribute('checked')) {
    $(this).removeAttr('checked');
    $(this).siblings('.radio').attr('checked', false);
  } else {
    $(this).attr('checked', true);
    $(this).siblings('.radio').removeAttr('checked');
  }
});
Run Code Online (Sandbox Code Playgroud)

DEMO