Search code examples
hidehiddenvisible

show/hide a button inside form with javascript


I have started learning html , css, javascript just 3 weeks ago. Here is my first and very simple program. It has a form , the form has 3 buttons and nothing else. One of the buttons is initially hidden. Clicking on one of the other two buttons would make the hidden button visible. After making it visible, clicking on the third button would hide it again. Thats it , small simple program but it doesnt work. When I click the "show" button , the hidden button does not appear. I have been trying to fix it for 4 hours but I got no clue yet why its not working . Somebody help please. By the way I dont know nothing about jquery, so only javascript help please.

`

<meta charset="UTF-8" />
<title>Useless Form</title>

<script type="text/javascript" language="JavaScript">

    var hidden = true ;  

    function show() 
    {
         if (hidden) 
        {
           document.getElementById("third").style.visibility = 'visible';
           hidden = false ;          
        }
       else 
          {
              alert(" The button is already visible !") ;
          }
    }

    function hide() 
    {

       if (!hidden) 
        {
           document.getElementById("third").style.visibility = 'hidden';
           hidden = true ;

        }
       else 
          {
              alert(" The button is already hidden !") ;
          }
    }      


</script>

<style type="text/css">
 h1
{
    font-family: calibri;   
    text-align: center;         
}

button
{  
    color: blue   ;
    font-size: 1em ;
    margin-left: 133px;

}  

 table
 { 
   margin-top: 190px; 
 }

form
{

    position: absolute;
    top: 8%;
    bottom: 7%; 
    left: 15% ;
    right: 15% ;    
    color: #fb9  ;          
    background-color: #420 ;        
    border: 4px double #C96333  ;               
}   
body { background-color: #000 ; }

 <form>

 <h1> My utter useless form </h1> <br>

 <table>
   <tr>

     <td> <button    id="first"    onclick="show()"  >show</button> </td>
     <td> <button    id="second"   onclick="hide()">hide</button> </td>
     <td> <button    id="third"      hidden>effected</button> </td>

   </tr>
 </table>   

</form>

`


Solution

  • add the attribute: type="button" to all the buttons, or else the default attribute of type="submit" is used (causing an undesired page refresh).

    <button type="button">
    

    Then...

    Your javascript doesn't actually toggle the html hidden attribute. This should work instead

    show the element:

    document.getElementById("third").removeAttribute("hidden");
    

    hide the element:

    document.getElementById("third").setAttribute("hidden", 'true');
    

    Keep in mind, there are a multitude of methods to show and hide elements that you can research, but I'm conforming to your current design choice.