Search code examples
javascriptcheckbox

Change variable value when checkbox is checked/unchecked


I was trying to change the value of a variable according to the status of a checkbox:

<script type="text/javascript">
    if(document.getElementByType('checkbox').checked)
    {
        var a="checked";
    }
    else
    {
        var a="not checked";
    }
    document.getElementById('result').innerHTML ='result '+a;
</script>

<input type="checkbox" value="1"/>Checkbox<br/>
<br/>
<span id="result"></span>

What's the problem with this code?


Solution

  • Try this:

    if (document.querySelector('input[type=checkbox]').checked) {
    

    Demo here

    Code suggestion:

    <input type="checkbox" />Checkbox<br/>
    <span id="result"></span>
    <script type="text/javascript">
    window.onload = function () {
        var input = document.querySelector('input[type=checkbox]');
    
        function check() {
            var a = input.checked ? "checked" : "not checked";
            document.getElementById('result').innerHTML = 'result ' + a;
        }
        input.onchange = check;
        check();
    }
    </script>
    

    In your post you have the javascript before the HTML, in this case the HTML should be first so the javascript can "find it". OR use, like in my example a window.onload function, to run the code after the page loaded.