htmlcheckbox

return value unclicking html checkbox


I try to make a checkbox that should return true if I select it and false if I deselect it.

<input type="checkbox" id="10101" name="10101" 
onchange="update_C('10101', 40)" value="true">

and then I accsess the value inside update_C with

document.getElementById('10101').value

However, this always returns true, every time the checkbox gets selected or deselected.

I found some suggestions how to implement this, but they are quite old and I didn't manage to make them work. Are there any "new" solutions how this problem can be solved?

One work around would be using radio buttons with true/false values, but I would prefer checkboxes.


Solution

  • You can use the checked property to check if the checkbox is selected

    <!DOCTYPE html>
    <html lang="vi">
    <head>
        <meta charset="UTF-8">
        <title>Checkbox Example</title>
    </head>
    <body>
        <input type="checkbox" id="10101" name="10101" onchange="update_C('10101', 40)">
    
        <script>
            function update_C(id, value) {
                let isChecked = document.getElementById(id).checked;
                console.log(isChecked);
            }
        </script>
    </body>
    </html>