gpt4 book ai didi

javascript - jQuery 将选中的复选框存储到数组中

转载 作者:行者123 更新时间:2023-11-28 04:57:09 26 4
gpt4 key购买 nike

背景

我有一个复选框表格网格,按名称分组,每个复选框都包含一个时间值。 HTML 示例:

<td><input type="checkbox" name="tuesday[]" value="10am"></td>
<td><input type="checkbox" name="tuesday[]" value="11am"></td>
<td><input type="checkbox" name="tuesday[]" value="12pm"></td>
<td><input type="checkbox" name="tuesday[]" value="1pm"></td>
<td><input type="checkbox" name="tuesday[]" value="2pm"></td>
<td><input type="checkbox" name="tuesday[]" value="3pm"></td>
<td><input type="checkbox" name="tuesday[]" value="4pm"></td>
<td><input type="checkbox" name="tuesday[]" value="5pm"></td>
<td><input type="checkbox" name="tuesday[]" value="6pm"></td>
<td><input type="checkbox" name="tuesday[]" value="7pm"></td>

提交表单后,值将按我希望的方式POST;所有检查的时间都在 tuesday[] 数组中。

问题

我想用 jQuery 做一些客户端验证。我想检查是否至少选中了一个复选框。

我试过像这样将它存储到一个 var 中:

var availTuesday  = $("input:checkbox[name='tuesday']:checked");

但是当我这样做并且 console.log(availTuesday); 时,没有显示任何内容(无论是否检查了某些内容)。我也尝试过 console.log(availTuesday.serialize());

问题:

如何检索用户检查的 tuesday[] 复选框组以及其他日期(wednesday[]thursday)的值[] 等)?

谢谢。

最佳答案

选择器不正确,改成:

var $tuesday = $("input[type=checkbox][name='tuesday[]']:checked");

要获取值,您可以使用返回数组的 .map() 方法:

if ($tuesday.length) {
// Getting values of the checked checkboxes
var values = $tuesday.map(function(){
return this.value;
}).get();
// ...
} else {
// There is no checked `day[]` checkbox
}

如果您有其他类似的复选框集,您可以使用数组:

var days = ['days', 'in', 'a', 'week'],
values = {},
errors = [],
$checkboxes = $("input[type=checkbox]");

$.each(days, function(_, day) {
var $set = $checkboxes.filter('[name="'+day+'[]"]:checked');
if ($set.length) {
values[day] = $set.map(function() {
return this.value;
}).get();
} else {
// There is no checked `day[]` checkbox
errors.push(day);
}
});

if (errors.length) {
// console.log('Please check at least one hour in ' + errors.join(', ') + ' days ...');
} else {
// console.log(values);
}

关于javascript - jQuery 将选中的复选框存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892655/

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