简体   繁体   中英

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

This is my fiddle for selecting from 3 checkbox. I want to have the value of selected checkbox to on while the unchecked are value off . I write the default value to off and tried to change the value of checked to 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[]

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

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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