skip to Main Content

can I change the value of a checkbox using a Java script in the DOM of the browser page?

It is necessary that the value remains the next time the form is loaded.

I tried several methods, but it only worked to visually check the box. When you clicked again, the checkbox was updated to a real one, and when submitting the form, a message was displayed that there was no checkmark at all

2

Answers


  1. did you try using an if statement to check/change the value?

    something like this could work:

    var checkB = document.getElementsByClassName("Checkbox-input");
    
    if (checkB.checked == true){
    checkB.value = 0;
    } else if (checkB.checked == false){
    checkB.value = 1;
    }
    

    (i just used 0 and 1 as an example)

    Login or Signup to reply.
  2. You want to be able to set the checkbox. Here’s a function that I named toggle which receives a checkbox element and a value and if the value is 'checked' then it checks the checkbox, otherwise it unchecks it.

    function toggle(context, value) {
        context.checked = (value === "checked");
    }
    <input type="checkbox" id="foo">
    <select onchange="toggle(document.getElementById('foo'), this.value)">
        <option value="unchecked">unchecked</option>
        <option value="checked">checked</option>
    </select>

    So, when you load your form and it gets clear what to do with the checkbox, just trigger toggle with the right parameters.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search