LoginSignup
0
1

requiredで複数チェックボックスを、1つ以上のチェックを必須にする 備忘録#4

Posted at

シンプルな使い方

HTML
<table border="1">
    <tr>
      <th>商品</th>
      <th>値段</th>
    </tr>
    <tr>
      <td>
+        <input type="text" name="name" required>
      </td>
      <td>
+        <input type="text" name="price" required>
      </td>
    </tr>
  </table>

このように、inputタグないにrequiredとすることによって、
テキストエリアに入力されず、登録ボタンを押された場合、以下のような表示になります。

スクリーンショット 2024-06-22 14.33.09.png

セレクトボックスの場合

  <h3 style="margin-bottom: 0;">カテゴリー</h3>
+  //チェックボックスにクラス属性をつける
 <input type="checkbox" name="genre" class="genre-selection"><input type="checkbox" name="genre"  class="genre-selection">DVD
 <input type="checkbox" name="genre"  class="genre-selection">ゲーム
 <input type="checkbox" name="genre"  class="genre-selection">楽器
    
 
  <table border="1" style="margin-top: 30px;">
     <tr>
       <th>商品</th>
       <th>値段</th>
     </tr>
     <tr>
       <td>
         <input type="text" name="name" required>
       </td>
       <td>
         <input type="text" name="price"required>
       </td>
     </tr>
   </table>
  <button>登録</button>
  </form>
  
  <!-- 判定のため、JavaScriptを追加 -->
  <script>
      (() => {
          // チェックボックスのinputタグを取得
          const checkBoxElements = Array.from(document.getElementsByClassName("genre-selection"));
  
          const errorMessage = "1つ以上の選択肢を選択してください。";
          checkBoxElements
              .forEach(m => {
                  // エラーメッセージを、カスタムなものに変更
                  m.setCustomValidity(errorMessage);
  
                  // 各チェックボックスのチェックのオン・オフ時に、以下の処理が実行されるようにする
                  m.addEventListener("change", () => {
                      // 1つ以上チェックがされているかどうかを判定
                      const isCheckedAtLeastOne = document.querySelector(".genre-selection:checked") !== null;
  
                      // 1つもチェックがされていなかったら、すべてのチェックボックスを required にする
                      // 加えて、エラーメッセージも変更する
                      checkBoxElements.forEach(n => {
                          n.required = !isCheckedAtLeastOne
                          n.setCustomValidity(isCheckedAtLeastOne ? "" : errorMessage);
                      });
                  });
              });
      })();
  </script>

これでできる。

参考サイト

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