View or hide an element with javascript codes using the.display style

Asked

Viewed 80 times

-1

I built a code that when the condition is true shows the component on the screen and when it is false hides the component. When the condition is false the first time it hides, but changing to true condition the component does not appear.

Follow the code below:

function VerificarDeposito(){

    if ($('#DadosComplementares').val()=="SIM"){

        document.getElementById('Painel4').style.display = 'true';
    }else{
        document.getElementById('Painel4').style.display = 'none'; 
    };
}
  • Good afternoon! I saw that you canceled my answer. This is no problem, but if you can say if it didn’t work I would like to improve it. Obg!

2 answers

1


If the value of the widget is never changed, it will never appear again. Change the value of the widget to toggle the visibility:

function VerificarDeposito(){
    if ($('#DadosComplementares').val()=="SIM"){
        $('#DadosComplementares').val("NÃO");
        $('#Painel4').show();
    }else{
        $('#DadosComplementares').val("SIM");
        $('#Painel4').hide(); 
    };
}

Example:

function VerificarDeposito(){
    if ($('#DadosComplementares').val()=="SIM"){
        $('#DadosComplementares').val("NÃO");
        $('#Painel4').show();
    }else{
        $('#DadosComplementares').val("SIM");
        $('#Painel4').hide(); 
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="VerificarDeposito()">Verificar</button>
<br>
<input type="text" value="NÃO" id="DadosComplementares" />
<br>
<div id="Painel4">
   painel4
</div>

1

If you’re using jQuery, why use the getElementById?

You can use the show and hide of jQuery also, so:

if ($('#DadosComplementares').val()=="SIM") {
    $('#Painel4').show();
} else {
    $('#Painel4').hide(); 
};
  • interesting how people vote in the answer as negative without at least informing what is not useful in it

  • 1

    That’s true, I try to improve the question to see if the votes change, but this difficult.

Browser other questions tagged

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