jquery チェックボックスの全選択・全解除を行う

jquery チェックボックスの全選択・全解除を行う

jqueryでチェックボックスの全選択・全解除を行うサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.6.0
  • Apache 2.4.43
  • ブラウザ chrome 91.0.4472.77

チェックボックスの全選択・全解除

propを使用して「checked」の状態を切り替えます。
ここではボタンをクリックすると、チェックボックスの全選択・全解除を行うサンプルコードを記述してます。

※デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <!-- semantic.js  -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
  <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
  body>.grid {
    height: 100%;
  }
</style>
<script>

  $(document).ready(function () {

    $('#btn').on('click', function () {
      $('input[type=checkbox]').prop( 'checked', true );
    });

    $('#btn2').on('click', function () {
      $('input[type=checkbox]').prop( 'checked', false );
    });

  });

</script>

<body>

  <div class="ui middle aligned center aligned grid">
    <div class="column">

      <div class="field">
        <input type="checkbox" name="example">
        <label>one</label>

        <input type="checkbox" name="example">
        <label>two</label>

        <input type="checkbox" name="example">
        <label>three</label>
      </div>
      <button id="btn" class="ui pink basic button">チェック</button>
      <button id="btn2" class="ui pink basic button">解除</button>
    </div>
  </div>
</body>

</html>

チェックボックスが切り替えされることが確認できます。