Show Hide Javascript Button

Asked

Viewed 1,291 times

0

I’m having trouble implementing the function of showing and hiding a div in HTML with Javascript.

What I need is that when a return from me servlet is empty or null, hide a certain div. The same should happen in reverse, for example, when the return of the servlet is not empty or different from null, to div appears.

Follow part of my code:

  • This is the div that I want to hide or show and the method JavaScript

 <script type="text/javascript">
                                    var a = '<%=a.getSoldes()%>';
                                    if (a !== null && a !== undefined) {
                                        document.getElementById('descricaosolucao').style.display = "block";
                                    } else {
                                        document.getElementById('descricaosolucao').style.display = "none";
                                    }
                                </script>
<div id="descricaosolucao" class="descricaosolucao" style="display: none;">
                                        <p class="titulo-comp">Solução<%=dataSol%></p>
                                        <p ><%=a.getSoldes()%></p>
                                    </div>

I have little knowledge in Javascript and so I would like your help.

From now on, thank you.

  • That code <%=a.getSoldes()%> is that language? this is done on the server?

  • I don’t think it’s Asp ?

  • What comes in console.log(a)?

  • From the syntax it looks like jsp, server side

  • I am developing in Java WEB JSP and in code <%=a.getSoldes()%> should come a text. When it comes empty, the div should hide.

  • Why not do that if directly in JSP since it is not something that can change after the page is loaded ? You can do the if and apply a class css with display:none directly in the attribute class

  • Hello Isac. I’m a layman yet. Please, could you show me what it’s like in practice? How do I make the div receive the JSP parameter?

Show 2 more comments

2 answers

0

I believe the problem is in the if conditions that you are doing. Let’s say "a. getSoldes()" is empty, then the variable would look like this:

var a = '';

Both comparisons 'a !== null' and 'a !== Undefined' return true. If you change the if condition to 'a. length > 0' you will have the behavior you want.

0


If it is something that does not change after the page is loaded the best is to do it on the server side soon, putting directly the right style in the <div>.

<div id="descricaosolucao" class="descricaosolucao" style="${dataSol?'':'display: none;'}">
     <p class="titulo-comp">Solução<%=dataSol%></p>
     <p ><%=a.getSoldes()%></p>
</div>

In which I used a ternary operator directly on style:

style="${dataSol?'':'display: none;'}"

If dataSol is different from null is 'otherwise it is display:none; and therefore hides

Browser other questions tagged

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