jqueryでチェックボックスのバリデーションを作る

  • sample.ctp
<?= $this -> Form -> create('',['type' => 'get','url' => ['action' => 'action']])?>
<?= $this -> Form -> checkbox("select.check1",array('class'=> 'select')) ?>りんご 
<?= $this -> Form -> checkbox("select.check2",array('class'=> 'select')) ?>バナナ 
<?= $this -> Form -> checkbox("select.check3",array('class'=> 'select')) ?>みかん
<?= $this -> Form -> button('submit',array('type' => 'submit')) ?>
<?= $this -> Form - > end(); ?>
  • sample.js
$(function() {
    "use strict";
    $('form').submit(function() {
        //少なくとも1つはチェックがあるかどうか 使いたいフォームのクラス名を指定
        if($('.select:checked').val() !== '1' ) {
            // 警告を出す
            window.alert('ジャンルを選択してください。');
            // 処理を中断 遷移しない
            return false;
        }
    //配列で取得する場合はつける
    }).get();
});

qiita.com