Searching and changing the value of checkboxes with javascript

2

I'm trying to fetch and change the values of a checkbox using Javascript. The intention is, when the JS function is called, check that the checkbox is set. If not, seven-a as checked, and vice versa. But when trying to read the state of the checkbox the following error is shown: "Can not read property 'checked' of null"

My last attempt so far was as follows:

<label for="letrasMinusculas">
<img src="images/checked.png" id="imgLetrasMinusculas" onclick="changeIcon(letrasMinusculas)">
</label>

<input id="letrasMinusculas" class="boxOculto" name="letrasMinusculas" type="checkbox" checked>

And in Javascript:

function changeIcon(id){
                           var status = document.getElementById(id);
                           if (status.checked){
                            alert("Verdadeiro");
                           }
                           else{alert("Falso");}
                    }

    
asked by anonymous 26.11.2015 / 11:56

1 answer

1

Your function is working correctly, what are you passing as id parameter? has to be 'letrasMinusculas' , in your else you can set checked = true if this is what you need.

Example:

function changeIcon(id) {
  var status = document.getElementById(id);
  if (status.checked) {
    alert("Verdadeiro");
  } else {
    alert("Falso");
    status.checked = true;
  }
}

changeIcon('letrasMinusculas');
<input id="letrasMinusculas" class="boxOculto" name="letrasMinusculas" type="checkbox" checked>
    
26.11.2015 / 12:09