チェックボックスをオンにしてボタンをクリックすることで
表示を切り替えることをしたいのですが挙動が思った通りになりません。
アドバイスいただけますと幸いです。
<やりたいこと>
・「結果を見る」をクリックするとチェックをした内容のみ表示。
・1つ以上チェックしていないと「結果を見る」が有効にならない。
・全てチェックで全体をオンオフできるように。
<うまくいかないこと>
・一度チェックをしてしまうと、チェックを解除しても「結果を見る」が有効になってしまう。
・全てチェックでオンオフした状態がその後の処理に反映しない。
コードはこちらにアップしています。
http://jsdo.it/wns/u5Di
<!doctype html> <html> <head> <meta charset="UTF-8"> <style> #favorite.choice li, #favorite.choice input.animal, #favorite.choice #bt_select, #favorite.choice #checked_all { display: none; } #favorite.choice li.show { color: #ff0000; font-weight: bold; display: block; } #bt_select { display: inline-block; padding: 10px 20px; } #bt_select.disabled { background-color: #eee; color: #333; } #bt_select.enabled { cursor: pointer; background-color: #ff0000; color: #fff; } </style> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script> jQuery(function($) { //全て選択 $('#checked_all input').on('change', function() { $('input.animal').prop('checked', this.checked); }); $('input.animal').click(function() { $(this).parent().parent().toggleClass('show'); if ($('input.animal:checked')[0]) { //1つ以上選択されていた場合 $('#bt_select').removeClass('disabled'); $('#bt_select').addClass('enabled'); } else { //1つも選択されていない場合 $('#bt_select').removeClass('enabled'); $('#bt_select').addClass('disabled'); } $('#bt_select.enabled').click(function() { $('#favorite').addClass('choice'); $('h1').text('あなたが選んだのはこちらです'); }); }); }); </script> </head> <body> <div id="favorite"> <h1>1つ以上選択してください</h1> <p id="checked_all"><label><input type="checkbox">すべてチェック</label></p> <ul> <li><label><input type="checkbox" name="好きな動物" value="パンダ" class="animal">パンダ</label></li> <li><label><input type="checkbox" name="好きな動物" value="ライオン" class="animal">ライオン</label></li> <li><label><input type="checkbox" name="好きな動物" value="キリン" class="animal">キリン</label></li> <li><label><input type="checkbox" name="好きな動物" value="ゾウ" class="animal">ゾウ</label></li> </ul> <p id="bt_select" class="disabled">結果を見る</p> </div> </body> </html>
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/27 08:46
2017/06/27 10:08
2017/06/27 10:57