checkbox 的取值

 

以下範例示範如何取出已勾選的選項

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
    <meta name="viewport" content="width=device-width">
</head>

<body>
    <div>
        <input type="checkbox" id="a" data-key="fruit" value="banana">
        <label for="a">香蕉</label>
        <input type="checkbox" id="b" data-key="fruit" value="apple">
        <label for="b">頻果</label>
        <input type="checkbox" id="c" data-key="fruit" value="guava">
        <label for="c">芭樂</label>
    </div>

    <script>
        var checkboxs = $('[data-key="fruit"]');
        checkboxs.on('change', event => {
            var content = new Array();
            var checked = $('[data-key="fruit"]:checked');
            for (let index = 0; index < checked.length; index++) {
                content.push($(checked[index]).val());
            }
            console.log(content.join(','));
        });
    </script>
</body>

</html>

額外一提,經由 script 可特定勾選某一選項

document.getElementById("a").checked = true;

$('#a').prop('checked', true);