skip to Main Content

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.

2

Answers


  1. You have set the value="true" and then ask for it. Therefore you get true no matter whether the checkbox is checked or not. You need to ask for propery checked.

    document.getElementById('10101').checked;
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search