复选框检查事件监听器


77

最近,我一直在使用Chrome Plugin API,并且我正在寻求开发一个插件,该插件将使我的网站管理工作变得更加轻松。

现在,我希望做的是在选中某个复选框时触发一个事件。由于该网站不属于我,因此我无法更改代码,因此我正在使用Chrome API。主要问题之一是,没有名称,而是名称。我想知道一旦选中带有“名称”的特定复选框,是否可以触发该功能。

Answers:


158

简短答案:使用change事件。这是几个实际的例子。由于我误解了问题,因此我将包括jQuery示例以及纯JavaScript。但是,使用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.filterArray.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>


6
Using the jQuery-like querySelector... mmm,不是“类似于jQuery的”(很想拒绝投票)
JFK

3
我的意思是jQuery在Javascript中广泛使用了查询选择器。在他们出现之前,选择和查找元素是一件麻烦的事。
thordarson

2
始终使用addEventListener而不是直接事件onchange来获得进一步的兼容性。
beytarovski

2
所有浏览器支持@dino onchange,除了可能适合您特定项目的用例之外,on [event]和addEventListener之间绝对没有区别。请告诉我,我的答案应该以什么样的方式被否决。它不能回答问题吗?
thordarson

7
@thordarsononchange没有添加事件监听器。它取代了现有的。这意味着您只能通过一个事件来阻止该对象,这可能不利于使用同一对象的其他插件或脚本。如果我有一个“开始聊天”按钮,我希望它被其他主题,插件或脚本所吸引。
beytarovski

48

由于我jQuery在OP中看不到该标记,因此这里是一个仅javascript选项:

document.addEventListener("DOMContentLoaded", function (event) {
    var _selector = document.querySelector('input[name=myCheckbox]');
    _selector.addEventListener('change', function (event) {
        if (_selector.checked) {
            // do something if checked
        } else {
            // do something else otherwise
        }
    });
});

参见JSFIDDLE


您说得对,我回想起您的答案。我使用querySelector方法添加了jQuery free选项。
thordarson

为什么将下划线添加到_selector变量中?
Linus

@Linus:没有技术原因。我相信在回答问题时,我正在与客户一起工作,在该客户中,函数中的所有私有变量都以下划线开头,我想我会不自觉地以相同的方式答复。它的工作原理一样,没有他们jsfiddle.net/13pog9L8 请注意有关变量的使用或不下划线,重要的是整个代码(你对你的工作或公司)的一致性
肯尼迪

1
您可以这样做:if(event.target.checked){//做某事} else {//做某事}
SabU

1
@SabU有成千上万的方法可以做同样的事情;)
肯尼迪国际

12

如果您的html中有一个复选框,例如:

<input id="conducted" type = "checkbox" name="party" value="0">

并且您想要使用javascript将EventListener添加到此复选框,在关联的js文件中,您可以执行以下操作:

checkbox = document.getElementById('conducted');

checkbox.addEventListener('change', e => {

    if(e.target.checked){
        //do something
    }

});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.