Searching and changing the value of the checkbox with javascript

Asked

Viewed 1,939 times

2

I’m trying to search and change the values of a checkbox using Javascript. The intention is, when the JS function is called, to check if the checkbox is set. If not, seven-a as checked, and vice versa. However, when trying to read the checkbox state the following error is shown:"Cannot 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");}
                    }

Note: The checkbox receives the class "boxOculto" (display: None) because I prefer to use a label with image for the user to click for customization.

  • 2

    Tried to pass ID as string? like this onclick="changeIcon('letrasMinusculas')" ?

  • That was the mistake. Thank you very much for your help.

1 answer

1

Your function is working properly, what are you passing as parameter id ? has to be 'letrasMinusculas', in your This you can set checked = true if this is what you really 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>

  • 1

    Dude, that’s exactly it. It worked right here. Thanks. I just didn’t need to set it to "true" because as my image is already a label for the checkbox, just click on it that same automatic arrow. But thanks even for the help.

  • @Matheusgodoi Glad it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.