1. ホーム
  2. javascript

[解決済み] チェックボックスチェックイベントリスナー

2022-11-21 07:33:02

質問

最近、私はChrome Plugin APIで作業しており、ウェブサイトを管理するために私の生活を容易にするプラグインを開発したいと考えています。

今私がしたいことは、あるチェックボックスがチェックされたときにイベントを発生させることです。 この Web サイトは私のものではないため、コードを変更することはできませんので、Chrome API を使用しています。主な問題の1つは、IDがあるのではなく、名前があることです。私は、「名前」を持つ特定のチェックボックスがチェックされると、関数を起動することができるかどうかを考えていました。

どのように解決するのですか?

簡単な答えです。この場合 change というイベントがあります。ここにいくつかの実用例があります。質問を読み違えたので、プレーンなJavaScriptと一緒にjQueryの例も載せておきます。jQueryを使っても、あまり得るものはないでしょうけど。

単一のチェックボックス

使用方法 querySelector .

var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});
<input type="checkbox" name="checkbox" />

jQueryでシングルチェックボックス

$('input[name=checkbox]').change(function() {
  if ($(this).is(':checked')) {
    console.log("Checkbox is checked..")
  } else {
    console.log("Checkbox is not checked..")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="checkbox" />

複数のチェックボックス

チェックボックスの一覧の例です。複数の要素を選択するために querySelectorAll の代わりに querySelector . 次に Array.filter そして Array.map でチェックされた値を抽出します。

// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []

/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/

// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function() {
    enabledSettings = 
      Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
      .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
      .map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
      
    console.log(enabledSettings)
  })
});
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>

jQueryで複数のチェックボックス

let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];

// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
  enabledSettings = checkboxes
    .filter(":checked") // Filter out unchecked boxes.
    .map(function() { // Extract values using jQuery map.
      return this.value;
    }) 
    .get() // Get array.
    
  console.log(enabledSettings);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>