选中所有复选框,并将复选框的值设置为'on'jquery

时间:2015-06-16 04:33:24

标签: javascript jquery html checkbox

This 是我从3复选框中选择的小提琴。我希望将所选复选框的值设为on,而未选中的值为off。我将默认值写为off,并尝试将checked的值更改为on。任何建议表示赞赏

2 个答案:

答案 0 :(得分:3)

问题是cfx runif ($("input[name='resolution[]']:checked")) {将返回一个jQuery对象,该对象将包含名称为$("input[name='resolution[]']:checked")

的所有选中复选框

你需要

resolution[]

演示:Fiddle

答案 1 :(得分:2)

使用以下代码片段来达到预期效果。

<强> 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