在 jQuery 中获取复选框值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2834350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:21:59  来源:igfitidea点击:

Get checkbox value in jQuery

jqueryhtmlformscheckbox

提问by maztt

How can I get a checkbox's value in jQuery?

如何在 jQuery 中获取复选框的值?

回答by Sarfraz

To get the value of the Value attribute you can do something like this:

要获取 Value 属性的值,您可以执行以下操作:

$("input[type='checkbox']").val();

Or if you have set a classor idfor it, you can:

或者,如果您为它设置了classid,您可以:

$('#check_id').val();
$('.check_class').val();

However this will return the samevalue whether it is checked or not, this can be confusing as it is different to the submitted form behaviour.

然而,无论是否检查,这都会返回相同的值,这可能会令人困惑,因为它与提交的表单行为不同。

To check whether it is checked or not, do:

要检查它是否被选中,请执行以下操作:

if ($('#check_id').is(":checked"))
{
  // it is checked
}

回答by Alain Tiemblo

Those 2 ways are working:

这两种方式正在起作用:

  • $('#checkbox').prop('checked')
  • $('#checkbox').is(':checked')(thanks @mgsloan)
  • $('#checkbox').prop('checked')
  • $('#checkbox').is(':checked')(谢谢@mgsloan

$('#test').click(function() {
    alert("Checkbox state (method 1) = " + $('#test').prop('checked'));
    alert("Checkbox state (method 2) = " + $('#test').is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check me: <input id="test" type="checkbox" />

回答by RDK

Try this small solution:

试试这个小解决方案:

$("#some_id").attr("checked") ? 1 : 0;

or

或者

$("#some_id").attr("checked") || 0;

回答by Reza

The only correct ways of retrieving a checkbox's value is as following

检索复选框值的唯一正确方法如下

if ( elem.checked ) 
if ( $( elem ).prop( "checked" ) ) 
if ( $( elem ).is( ":checked" ) ) 

as explained in the official documentations in jQuery's website. The rest of the methods has nothing to do with the propertyof the checkbox, they are checking the attribute which means they are testing the initial state of the checkbox when it was loaded. So in short:

如 jQuery 网站的官方文档中所述。其余的方法与复选框的属性无关,它们正在检查属性,这意味着它们正在测试加载时复选框的初始状态。简而言之:

  • When you have the element and you know it is a checkbox you can simply read its property and you won't need jQuery for that (i.e. elem.checked) or you can use $(elem).prop("checked")if you want to rely on jQuery.
  • If you need to know (or compare) the value when the element was first loaded (i.e. the default value) the correct way to do it is $(elem).is(":checked").
  • 当您拥有该元素并且您知道它是一个复选框时,您可以简单地读取它的属性,并且您不需要 jQuery(即elem.checked),或者$(elem).prop("checked")如果您想依赖 jQuery,则可以使用它。
  • 如果您需要知道(或比较)第一次加载元素时的值(即默认值),那么正确的做法是$(elem).is(":checked").

Answers are misleading, Please check below yourself:

答案有误导性,请自行检查以下内容:

http://api.jquery.com/prop/

http://api.jquery.com/prop/

回答by Greg A

Just to clarify things:

只是为了澄清事情:

$('#checkbox_ID').is(":checked")

Will return 'true' or 'false'

将返回“真”或“假”

回答by Nalan Madheswaran

$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();

回答by Jaskaran singh Rajal

jQuery(".checkboxClass").click(function(){
        var selectedCountry = new Array();
        var n = jQuery(".checkboxClass:checked").length;
        if (n > 0){
            jQuery(".checkboxClass:checked").each(function(){
                selectedCountry.push($(this).val());
            });
        }
        alert(selectedCountry);
    });

回答by Kevin Shea

Simple but effective and assumes you know the checkbox will be found:

简单但有效,假设您知道会找到复选框:

$("#some_id")[0].checked;

Gives true/false

true/false

回答by Kamal

//By each()
var testval = [];
 $('.hobbies_class:checked').each(function() {
   testval.push($(this).val());
 });


//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");

 //HTML Code

 <input type="checkbox" value="cricket" name="hobbies[]"  class="hobbies_class">Cricket 
  <input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey

Example
Demo

示例
演示

回答by Josh Crozier

Despite the fact that this question is asking for a jQuery solution, here is a pure JavaScript answer since nobody has mentioned it.

尽管这个问题需要一个 jQuery 解决方案,但这里是一个纯 JavaScript 答案,因为没有人提到它。

Without jQuery:

没有 jQuery:

Simply select the element and access the checkedproperty(which returns a boolean).

只需选择元素并访问checked属性(返回布尔值)。

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

alert(checkbox.checked);
<input type="checkbox"/>



Here is a quick example listening to the changeevent:

这是一个侦听change事件的快速示例:

var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function (e) {
    alert(this.checked);
});
<input type="checkbox"/>



To select checked elements, use the :checkedpseudo class(input[type="checkbox"]:checked).

要选择选中的元素,请使用:checked伪类( input[type="checkbox"]:checked)。

Here is an example that iterates over checked inputelements and returns a mapped array of the checked element's names.

这是一个迭代已检查input元素并返回已检查元素名称的映射数组的示例。

Example Here

示例在这里

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);
<div class="parent">
    <input type="checkbox" name="name1" />
    <input type="checkbox" name="name2" />
    <input type="checkbox" name="name3" checked="checked" />
    <input type="checkbox" name="name4" checked="checked" />
    <input type="checkbox" name="name5" />
</div>