JavaScript Error in Chekar asp: CheckBox

1

Good morning. I have the following code:

HTML:

<asp:CheckBox ID="ckPergunta" runat="server" onchange='SelectChoices(this);' />

JavaScript:

<script type="text/javascript">
    SelectChoices();
    function SelectChoices() {
        var opc = document.getElementById('<%=ckPergunta.ClientID%>').checked;
        if (opc == false) {
            document.getElementById('<%=dlTipoResposta.ClientID %>').style.display = "none";
            document.getElementById('<%=txtRes.ClientID %>').style.display = "none";
        }
        else {
            document.getElementById('<%=dlTipoResposta.ClientID %>').style.display = "block";
            document.getElementById('<%=txtRes.ClientID %>').style.display = "block";
        }
    }
</script>

It happens that when I check, in checkBox the JavaScript code does not run. In other words, nothing happens. But if I put an onChange in an asp: TextBox the JavaScrip code works fine. What's wrong?

    
asked by anonymous 26.11.2015 / 13:46

1 answer

0

You are trying to call a function before it is instantiated, so the Script throws an exception and the Function is never created, so the following change should already solve:

function SelectChoices() {
    var opc = document.getElementById('<%=ckPergunta.ClientID%>').checked;
    if (opc == false) {
        document.getElementById('<%=dlTipoResposta.ClientID %>').style.display = "none";
        document.getElementById('<%=txtRes.ClientID %>').style.display = "none";
    }
    else {
        document.getElementById('<%=dlTipoResposta.ClientID %>').style.display = "block";
        document.getElementById('<%=txtRes.ClientID %>').style.display = "block";
    }
}
SelectChoices();

In any case, I advise you to make some changes to the code (just to improve performance a bit and help organize it), first remove any inline scripting from the HTML, and then avoid querying the DOM Elements, finally try not to use styles inline, use classes for it.

JavaScript

var ckPergunta = document.getElementById('<%= ckPergunta.ClientID%>');
var dlTipoResposta = document.getElementById('<%= dlTipoResposta.ClientID%>');
var txtRes = document.getElementById('<%= txtRes.ClientID%>');

var SelectChoices = function (event) {
  if (ckPergunta.checked) {
    dlTipoResposta.classList.add("invisivel");
    txtRes.classList.add("invisivel");
  } else {
    dlTipoResposta.classList.remove("invisivel");
    txtRes.classList.remove("invisivel");
  }
}

ckPergunta.addEventListener("change", SelectChoices );

CSS

.invisivel {
  display: none
}
    
26.11.2015 / 14:13