简体   繁体   English

选择所有复选框,并将选中复选框的值设置为“打开” jquery

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

This is my fiddle for selecting from 3 checkbox. 是我从3个复选框中进行选择的小提琴。 I want to have the value of selected checkbox to on while the unchecked are value off . 我希望将选中复选框的值设置为on ,而未选中的值设置为off I write the default value to off and tried to change the value of checked to on . 我将默认值写入off并尝试将checked的值更改为on Any suggestion is appreciated 任何建议表示赞赏

The problem is if ($("input[name='resolution[]']:checked")) { , $("input[name='resolution[]']:checked") will return a jQuery object which will contains all the selected checkboxes with name resolution[] 问题是if ($("input[name='resolution[]']:checked")) {$("input[name='resolution[]']:checked")将返回一个jQuery对象,其中包含所有选定的具有名称resolution[]复选框

You need 你需要

$('#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));
});

Demo: Fiddle 演示: 小提琴

Use below code Snippet to achieve expected result. 使用下面的代码片段可获得预期的结果。

HTML 的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: 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 小提琴结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM