-1

Please am a newbie in programming, I really need your help in this. Please how can I hide an HTML table then display it with a button using.JavaScript?

Imran
  • 103
  • 1
  • 7
  • 3
    Possible duplicate of [javascript hide/show element](http://stackoverflow.com/questions/6242976/javascript-hide-show-element) – XAMPPRocky May 05 '16 at 20:21

2 Answers2

1

Use document.querySelector to get the elements and the hidden attribute to show and hide the table. Use an event listener and listen for the click event on the button:

var table = document.querySelector("table");
table.hidden = true;

document.querySelector("button").addEventListener("click", function(event) {
  table.hidden = false;
});
table {
  text-align: center;
  border-collapse: collapse;
}
td,
th {
  padding: 0 5px;
  border: 1px solid black;
}
<table>
  <tr>
    <th>Day</th>
    <th>Rain</th>
  </tr>
  <tr>
    <td>1</td>
    <td>50 mm</td>
  </tr>
  <tr>
    <td>2</td>
    <td>21 mm</td>
  </tr>
  <tr>
    <td>3</td>
    <td>5 mm</td>
  </tr>
</table>
<button>Show</button>
metarmask
  • 1,747
  • 1
  • 16
  • 20
0

You can use a library called jQuery to do this extremely easily.

  • In your <head>, put <script src="code.jquery.com/jquery-latest.js></script>
  • Give your <table> an id, like this: <table id="myTable">
  • Add one button like this: <button onclick="$('#myTable').hide();">Hide</button>
  • And another like this: <button onclick="$('#myTable').show();">Show</button>

This will allow you to toggle the table's visibility.

I started writing this before @metarmask posted - his/her answer is much better, so you should probably take his/her advice.

Orisun
  • 19
  • 6