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()
で伝播させないようにします。
参考