0
0

More than 3 years have passed since last update.

【jquery】チェックボックスによるフォームの表示・非表示

Last updated at Posted at 2020-11-09

やりたい事

・チェックボックスが1つでもチェックされていたら入力フォームを表示

・チェックボックスが1つもチェックされていなかったら入力フォームを非表示

実践

■初期表示
使用フォーム
名前
メールアドレス
住所

■初期非表示
変更理由

※デザインはなし

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>
.file_box{
  display: none;
}
</style>
<body>
  <dl class="cf">
    <dt class="title">
      名前
      <input type="checkbox" class="ch" name="subscribe" value="1">
    </dt>
    <dd class="data ">
      <input class="input" type="text" name="name" value="">
    </dd>
    <dt class="title">
      メールアドレス
      <input type="checkbox" class="ch" name="subscribe" value="2">
    </dt>
    <dd class="data ">
      <input class="input" type="text" name="mail" value="" maxlength="128">
    </dd>
    <dt class="title">
      住所
      <input type="checkbox" class="ch" name="subscribe" value="3">
    </dt>
    <dd class="data ">
      <input class="input" type="text" name="address" value="" maxlength="128">
    </dd>
    <div class="ch_box">
      <dt class="title">
        変更理由
      </dt>
      <dd class="data ">
        <textarea class="input ch_text" type="text" name="address" value=""></textarea>
      </dd>
    </div>
  </dl>
</body>
</html>

続いて、jquery

    $(function () {
      $(".ch").change(function () {
        var ch_checked = $(this).prop('checked');
        if (ch_checked) {
          $('.ch_box').css("display", "block");
        }
        if ($(".ch:checked").length == 0) {
          $('.ch_box').css("display", "none");
          $('.ch_text').val("");
        }
      });
    });

手順
①3つのチェックボックスに同名のclass名を付与
②どれか1つでも選択されたら入力フォームを表示
1つ以上の条件の方が統一いているかも・・
③チェックボックスのチェックが0ならボックスを隠し、内容を初期化

以上

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