JavaScript:如何检测是否选中了HTML复选框? [英] JavaScript: How to detect if an HTML checkbox was selected?

查看:110
本文介绍了JavaScript:如何检测是否选中了HTML复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何:

  1. 检测是否已单击/选中HTML复选框吗?
  2. 获取已选中的复选框?

示例代码:

<FORM ACTION="...">
<INPUT TYPE=CHECKBOX VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="4+">4+ bedrooms<P>
</FORM>

含义

  1. 如果网络用户选择"1间卧室",我希望触发一个事件来通知我用户选择了"1间卧室".
  2. 如您所见,用户可以选择多个复选框.例如,他们可能想要查看具有"1卧室"或"2卧室"的房屋.因此,他们将同时选中两个复选框.选择多个复选框后,如何检索复选框值?

如果有帮助,我愿意使用JQuery简化这一过程.

In case it helps, I would be open to using JQuery to simplify this.

推荐答案

jQuery可以解救! (因为您已将其标记为此类):

jQuery to the rescue! (since you tagged it as such):

$('input:checkbox[name=bedrooms]').click(function() {
  var values = $('input:checkbox[name=bedrooms]:checked').map(function() {
    return this.value
  }).get();

  // do something with values array
})

(请确保在HTML中为复选框添加name="bedrooms"属性;无论如何,提交表单时都将需要它们,以便在服务器上检索它们.)

(make sure to add a name="bedrooms" attribute in the html for your checkboxes; you'll need them when submitting the form anyway, in order to retrieve them on the server).

我使用了一些伪选择器:

I've used a few pseudo-selectors:

  • "input:checkbox" finds all the input checkboxes on the page
  • "[name=bedrooms]" finds all the elements with attribute name="bedrooms"
  • ":checked" finds all the elements with attribute checked=true

将它们组合为"input:checkbox[name=bedrooms]:checked",jQuery会为您提供所有选中的复选框.

Combine them as "input:checkbox[name=bedrooms]:checked" and jQuery gives you all the checked checkboxes.

对于每一个我将其value属性拔出到一个数组中,您都可以简单地进行迭代结束并做您想做的事.

For each one I pluck out their value attribute into an array you can simply iterate over and do what you wish.

修改

您可以优化此代码以保存对复选框的引用,而不是告诉jQuery每次单击时都将其全部获取:

You can optimize this code to save a reference to your checkboxes instead of telling jQuery to go fetch them all everytime there's a click:

var $checkboxes = $('input:checkbox[name=bedrooms]');
$checkboxes.click(function() {
  var values = $checkboxes
    .filter(function() { return this.checked })
    .map(function() { return this.value })
    .get();

  // do something with values array
})

在此示例中,我已将复选框保存到var $checkboxes中.在单击任何复选框时,我们只需回过滤器 $checkboxes,直到仅选中的复选框,然后对每个提取value属性放入数组. get()只是将"jQueryized"数组转换为常规JavaScript数组的一项晦涩要求.

In this sample I've saved the checkboxes into var $checkboxes. On click of any checkbox, instead of going back to the DOM to grab the checked ones, we simply filter $checkboxes down to only the checkboxes that are checked, and for each one pluck out the value attribute into an array. The get() is just an obscure requirement to convert the "jQueryized" array to a regular JavaScript Array.

这篇关于JavaScript:如何检测是否选中了HTML复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆