TheWalkingPlay2500 TheWalkingPlay2500 - 4 months ago 8
Javascript Question

Disabling an input when a checkbox is checked

I need to disable a cmp when a checkbox is checked, I tried this:



<script language="text/javascript">

var x = document.getElementById("SemPretencao").checked;

function desativar() {

if (x==true) {
alert("Seu Babacaum");
document.getElementById("salario").disabled=true;
} else {
alert("Babaquara");
document.getElementById("salario").disabled=false;
}

}

document.getElementById("SemPretencao").addEventListener("click", desativar();, false);

</script>

inputs:

<a class="field_names">Pretenção Salarial: </a> <input type="number" class="number_inputs" name="salario" id="salario"> <br>
<a class="field_names">Não Tenho Pretenção Salarial </a> <input type="checkbox" class="checkbox_input" name="SemPretencao" id="SemPretencao">





Sorry for my English, I'm Brazilian.

Answer

Your addEventListener is wrong. You're calling the function instead of passing it. Your function can also be simplified a bit. Try this:

function desativar() {
  document.getElementById("salario").disabled = document.getElementById("SemPretencao").checked;
}

document.getElementById("SemPretencao").addEventListener("click", desativar, false);

Working example