0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

選択解除可能なラジオボタン

Posted at

1個しか選択させたくないけど、0個の選択肢も許容させたい
ってことで選択解除可能なラジオボタンをjQueryで実装しました。

コード

HTML
<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="radio1" checked>1
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="radio2" checked>2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="radio3" checked>3
  </label>
</div>
jQuery
$(".btn").click(function() {
  if ($(this).hasClass('active')) {
    event.stopImmediatePropagation();
    event.preventDefault();
    $(this).removeClass('active');
    $('input:radio', this).prop('checked', false);
  }
});

説明

event.preventDefault()でラジオボタンのデフォルトの動きを妨げます。
だけど、Bootstrapを入れているとbutton.jsが起動してしまうのでそっちも止めるためにevent.stopImmediatePropagation()で伝播させないようにします。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?