select 所有复选框和已选中复选框的值 'on' jquery

select all checkbox and have the value of checked checkbox to 'on' jquery

This 是我的 fiddle,用于从 3 个复选框中进行选择。我想让选中的复选框的值为 on,而未选中的值为 off。我将默认值写入off,并尝试将checked的值更改为on。任何建议表示赞赏

问题是 if ($("input[name='resolution[]']:checked")) {$("input[name='resolution[]']:checked") 将 return 一个 jQuery 对象,该对象将包含名称为 resolution[][=15= 的所有选定复选框]

你需要

$('#res').click(function () {
    var resolutiontemp = {};
    var resolution = [];
    $("input[name='resolution[]']").each(function () {
        this.value = this.checked ? 'on' : 'off';
        var resolution = $(this).parent().find('span').text();
        resolutiontemp[resolution] = this.value;
    })
    resolution.push(resolutiontemp);
    console.log(JSON.stringify(resolution));
});

演示:Fiddle

使用下面的代码片段来实现预期的结果。

HTML

<table>
    <tr>
        <td>
            <input type="checkbox" id="res1" name="resolution[]" class="resolution" value="off"/><span>res 1 </span>

        </td>
        <td>
            <input type="checkbox" id="res2" name="resolution[]" class="resolution" value="off"/><span>res 2</span>

        </td>
        <td>
            <input type="checkbox" id="res3" name="resolution[]" class="resolution" value="off"/><span>res 3</span>

        </td>
    </tr>
            <tr>
                <td colspan="3"><input type="checkbox" id="selecctall" name=""/><span>Select All</span></td>

            </tr>
</table>

JQuery:

$('#selectall').click(function(event) {  //on click 
    var resolutiontemp = {},resolution = [];
    if(this.checked) { 
        $("input[name='resolution[]'").each(function() { 
            this.checked = true;
            $(this).prop('value','on');
            var resolutionval = $(this).val();
            var resolution = $(this).parent().find('span').text();
            resolutiontemp[resolution] = resolutionval;
        });
    }else{
        $("input[name='resolution[]'").each(function() { 
            this.checked = false;
            $(this).prop('value','off');
            var resolutionval = $(this).val();
            var resolution = $(this).parent().find('span').text();
            resolutiontemp[resolution] = resolutionval;
        });         
    }
    resolution.push(resolutiontemp);
    console.log(JSON.stringify(resolution));
});

Fiddle Result