2

Tengo el siguiente código (muy sencillo)

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

Y funciona perfectamente, pero muestra el siguiente error

Error mostrado

Como he dicho antes, funciona. Pero necesito eliminar dicho error para compilar la primera vez.

2 respuestas 2

3

Tienes que castear/convertir el resultado de getElementById a HTMLInputElement para poder acceder a la propiedad checked:

var checkbox = <HTMLInputElement>document.getElementById(id);
if(!checkbox.checked)
{
   //...
}
1
0

Deberías utilizar mejor hasAttribute('checked') para comprobar si está marcado y `setAttribute('checked', true)' para marcarlo:

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>

Referencia:

checked - MDN

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.