如何在页面加载时存储复选框的值和状态

How to store value and status of checkbox at pageload

本文关键字:复选框 状态 存储 加载      更新时间:2023-09-26

我希望在页面加载时存储复选框的值及其状态。当我提交表格时,我想检查前面的复选框"已选中"是否为"未选中";如果是这样,我需要将值保存在一个字符串中,以便在查询中用作列表。我尝试了以下内容,但我的语法有问题。请帮忙。

<input type="checkbox" name="Periods" value="25301601" />
<input type="checkbox" name="Periods" value="25301602"  checked />
<input type="button" id="buttonStore" value="Store">
<input type="button" id="buttonCompare" value="Compare">
$(document).ready(function() {
    $("#buttonStore").click(function () {
        // save status and value of all the checkboxes
        var periodCHK= [];
        $(":checkbox").each(function (){                            
            periodCHK["$(this).val()"]=($(this).is(':checked'));//does not store
             alert($(this).is(':checked'));
            alert($(this).val());
        });
        alert(periodCHK);//nothing
        }); 
     $("#buttonCompare").click(function () {     
        var periodstring; 
        $(":checkbox").each(function () {
            if (!$(this).is(':checked'))
                //if $(":checkbox").not(':checked')
            {
                //if this one was checked before, grab it and make a string
                if (periodCHK["$(this).val()"]) 
                {
                    periodstring+=["$(this).val()"] + ",";
                }
            }
            alert(periodstring); // does not loop
        });
    });
});

在以下语句中使用不带引号的$(this).val()。如果与引号一起使用,它将被视为字符串。

periodCHK[$(this).val()]