LoginSignup
1
0

More than 3 years have passed since last update.

iCheckを使用したチェックボックスでチェックの数を制限する方法

Posted at

iCheck.jsを使用したチェックボックスでチェックの数を制限したいと思ったのですが、
iCheckだと普通のclickやchangeイベントなどは使えないんですよね。

そこでiCheckの場合のチェックボックスのチェックの数を制限する方法をご紹介します。

前提として、jQueryとiCheck.jsは既に読み込んでいるものとします。

index.html
<div class="limit-checkbox-group">
  <label><input name="" value="その1" type="checkbox" class="flat">その1</label><br>
  <label><input name="" value="その2" type="checkbox" class="flat">その2</label><br>
  <label><input name="" value="その3" type="checkbox" class="flat">その3</label><br>
  <label><input name="" value="その4" type="checkbox" class="flat">その4</label><br>
  <label><input name="" value="その5" type="checkbox" class="flat">その5</label><br>
</div>
script.js
// ここはiCheckのカラー設定
$(function () {
    $('.limit-checkbox-group input[type="checkbox"].flat').iCheck({
      checkboxClass: 'icheckbox_flat-red',
      radioClass: 'iradio_flat-red'
    });
});

// ここのコードに注目(チェックは3つ制限)
$(".limit-checkbox-group").on("ifToggled", function() {
    checkboxes = $(this).find("input:checkbox");  
    if (checkboxes.filter(":checked").length >= 3) { 
        checkboxes.not(":checked").iCheck('disable'); 
    } else { 
        checkboxes.not(":checked").iCheck('enable');
    } 
});

解説

onchangeイベントではチェック状態変更の検知ができないので、ifToggledというイベントを使用します。
これでlimit-checkbox-groupクラスの範囲内で入力のチェック状態が変更されたのを検知できます。

次は$(this).find("input:checkbox")でチェックボックスを取得してcheckboxesに格納しています。
このcheckboxesfilterメソッドとlengthプロパティ使い、チェックされたチェックボックスの数を検出してif文で比較します。

チェックが既に3つであればiCheckのチェックボックスをdisableにして無効化に、
3つ未満であればiCheckのチェックボックスをenableにして有効化にしています。

参考にさせていただいたURL

iCheck.jsを使ってる時のchangeイベント
https://stackoverflow.com/questions/18906657/limit-number-of-checked-checkboxes-using-icheck

1
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
1
0