使用 jquery 检查多个复选框选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10285280/
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 09:05:19  来源:igfitidea点击:

Check multiple checkbox selection using jquery

jquerycheckboxselection

提问by coder

I am trying to find the easiest way to get the checkboxes that are selected.

我试图找到获取选中复选框的最简单方法。

Here's my script:

这是我的脚本:

$(document).ready(function() {
    $("input[name='chkTextEffects']").change(function() {
        if ($("#cbSolid").is(':checked') == true) {
            alert('Solid');
        } else if ($("#cbOutline").is(':checked') == true) {
           alert('Outline');
        } else if ($("#cbSolid", "#cbOutline").is(':checked') == true) {
            alert('SolidOutline');
        } else if ($("#cbSolid", "#cbOutline").is(':checked') == false) {
            alert('No Effects'); 
        }
    });
});?

HTML:

HTML:

   <input type="checkbox" name="chkTextEffects" id="cbSolid" value="Solid" />Solid
   <input type="checkbox" name="chkTextEffects" id="cbOutline" value="Outline" />Outline
   <input id="TextEffectsSelection" type="hidden" />

I'm not sure about this line if ($("#cbSolid", "#cbOutline").is(':checked') == true)or should I use bindto get that worked.

我不确定这条线,if ($("#cbSolid", "#cbOutline").is(':checked') == true)或者我应该用它bind来让它工作。

回答by SuperPomodoro

Here is an example I created that demonstrates what I think you're attempting to achieve:

这是我创建的一个示例,它展示了我认为您正在尝试实现的目标:

$('#getCheckboxesButton').live('click', function(event) {
    var checkboxValues = [];
    $('input[type="checkbox"]:checked').each(function(index, elem) {
        checkboxValues.push($(elem).val());
    });
    alert(checkboxValues.join(', '));
});

http://jsfiddle.net/qdvng/

http://jsfiddle.net/qdvng/

Let me know if that helps. Its basically using the ':checked' jQuery selector to retrieve checkboxes that are checked, then iterating through their values and printing it out.

如果这有帮助,请告诉我。它基本上使用 ':checked' jQuery 选择器来检索选中的复选框,然后遍历它们的值并将其打印出来。

回答by Craig

You can use the :checkedselector like this to get all checked checkboxes with the specified name:

您可以像这样使用:checked选择器来获取具有指定名称的所有选中的复选框:

$("input[name='chkTextEffects']:checked")

回答by Uchenna Nwanyanwu

Why not do this:

为什么不这样做:

$("#checkboxId").attr("checked") == "checked";