gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:56:57 25 4
gpt4 key购买 nike

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

例如,如果选中一项,则值为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com