簡體   English   中英

選擇所有復選框,並將選中復選框的值設置為“打開” jquery

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

是我從3個復選框中進行選擇的小提琴。 我希望將選中復選框的值設置為on ,而未選中的值設置為off 我將默認值寫入off並嘗試將checked的值更改為on 任何建議表示贊賞

問題是if ($("input[name='resolution[]']:checked")) {$("input[name='resolution[]']:checked")將返回一個jQuery對象,其中包含所有選定的具有名稱resolution[]復選框

你需要

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

演示: 小提琴

使用下面的代碼片段可獲得預期的結果。

的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));
});

小提琴結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM