Error selecting Checkbox

2

I have the following code (very simple)

    if (document.getElementById(id).checked == false) 
document.getElementById(id).checked = true;

And it works perfectly, but it shows the following error

As I said before, it works. But I need to eliminate that error to compile the first time.

    
asked by Mario López Batres 17.01.2018 в 13:58
source

2 answers

3

You have to cast / convert the result of getElementById to HTMLInputElement to be able to access the property checked :

var checkbox = <HTMLInputElement>document.getElementById(id);
if(!checkbox.checked)
{
   //...
}
    
answered by 17.01.2018 / 14:06
source
0

You should use better hasAttribute('checked') to check if it is marked and 'setAttribute (' checked ', true)' to mark it:

function check(){
  if (!document.getElementById('myCheck').hasAttribute('checked')) 
    document.getElementById('myCheck').setAttribute('checked' ,true);
}

document.getElementById('check').addEventListener('click', check);
<input type="checkbox" id="myCheck">

<button id="check">Check</button>

Reference:

checked - MDN

    
answered by 17.01.2018 в 14:07