LoginSignup
2
2

More than 5 years have passed since last update.

【JQuery】チェックボックスをラジオボタン風に実装する

Posted at

チェックボックスをラジオボタン風に実装する

よく忘れてしまうので、メモ程度に書いているのでご了承ください。

チェックボックスをラジオボタン風に実装する意味ってあるの?

よくディレクタなどにラジオボタンの機能でチェックボックスを作って欲しいと言われるが、
本当に必要なのでしょうか?
ディレクタいわく、1つだけチェックを入れさせたいが取り外しもさせたい。だそうです。

なので実装してみました。

html
<ul class="js-checkbox-radio">
<li><label><input type="checkbox" class="hogehoge" value="1"><span>1</span></label></li>
<li><label><input type="checkbox" class="hogehoge" value="2"><span>2</span></label></li>
<li><label><input type="checkbox" class="hogehoge" value="3"><span>3</span></label></li>
</ul>
jQuery
$('.js-checkbox-radio').on('click','.hogehoge',function() {
  if ($(this).prop('checked')){
    $(this).parents('.js-checkbox-radio').find('.hogehoge').prop('checked', false);
    $(this).prop('checked', true);
  }
});

この機能を複数箇所に入れる事を前提に書いてますので、もっと省略出来ると思いますがあしからず。

2
2
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
2
2