javascript - jQuery - 选中的复选框值(链接 jQuery 函数与 If 语句)

标签 javascript jquery html checkbox

我有多个复选框,并希望获得它们的总体值。

例如,如果选中一项,则值为 true/selected。

如果没有检查,则为 false/未检查。

我的 HTML 是:

<input id="one" type="checkbox">
<input id="two" type="checkbox">
<input id="three" type="checkbox">
<input id="four" type="checkbox">
<button onclick="check();">Is checked (jQuery Chained)</button>
<button onclick="check2();">Is checked(Big If Statement)</button>

我的 JavaScript/jQuery 是:

function check() {
    var booleee = $('#one,#two,#three,#four').attr('checked');
    alert("Checked: " + booleee);
}

function check2() {
    if ($('#one').attr('checked') || $('#two').attr('checked') || $('#three').attr('checked') || $('#four').attr('checked')) {
        alert("Checked: true");
    }
    alert("Checked: false");
}

Js fiddle :Click Here

请注意,我已经解决了这个问题。这个问题更多的是帮助我理解为什么我的 checked2() 函数可以工作,而我的 check() 却不能。

最佳答案

var booleee = $('#one,#two,#third,#four').attr('checked'); 仅检查第一个(在本例中 #一个)复选框被选中。

来自doc for attr

Get the value of an attribute for the first element in the set of matched elements.

应该是

var booleee = $('#one,#two,#three,#four').filter(':checked').length > 0;

此外,在新版本 (>1.6) 中,您需要使用属性“checked”(.prop('checked')),而不是您的替代方案中的 attr有一个:checked filter所以 .is(':checked').

关于javascript - jQuery - 选中的复选框值(链接 jQuery 函数与 If 语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18378591/

相关文章:

javascript - 如何将 iframe 加载与父页面加载同步

javascript - 为什么 JQuery 自动完成结果不显示在浏览器中?

javascript - 如何在动态创建的按钮的单击事件上执行 javascript 函数。

javascript - 使用 jQuery 更改文本

javascript - 在 Node.js 中获取未定义的读取属性错误

jquery - 将加载图像添加到网站

php - 从 iframe 中的表单获取数据

javascript - 突出显示包含相同列信息的数据表行

javascript - 如何修复 jaggery-js 生成的字符编码?

jquery - 如何在 Bootstrap 选择控件中设置文本的垂直对齐方式?