I have a button and a table on my webpage. I want to view the table when I click that button. I have tried it using javascript but the table only appears for a split second and then disappears. following is the code for my table:


var button = document.getElementById('BtnNextInsured'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('tblContact');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }
};
<button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show:

<table id="tblContact" class="table table-light table-borderless" style="display:none;">
  <tr>
    <td class="cellContent">
      <input id="txtEmail" class="txt" placeholder="Email" />
    </td>
    <td class="cellContent">
      <input id="txtCell" class="txt" placeholder="Cell Phone" />
    </td>
    <td class="cellContent">
      <input id="txtLandline" class="txt" placeholder="Landline" />
    </td>
  </tr>

  <tr>
    <td colspan="3" style="text-align: right">
      <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button>
    </td>
  </tr>
</table>



I don't understand what's wrong with my code. I am a beginner to javascript.

Table only appears for a split second on button click
as comments saying better using eventlistener.
with the eventlistene, you can use the event and like here stop it to avoid double click.
to appear disappear use a class 'hide' so you can toggle it, easier than than checking display none.


const tableAppear = () => {
  document.querySelector('#BtnNextInsured').addEventListener('click', evt => {
    evt.stopImmediatePropagation();
    document.querySelector('#tblContact').classList.toggle('hide');
  });
}
window.addEventListener('load', tableAppear);
.hide {
  display: none;
}
<button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show:

<table id="tblContact" class="table table-light table-borderless hide">
  <tr>
    <td class="cellContent">
      <input id="txtEmail" class="txt" placeholder="Email" />
    </td>
    <td class="cellContent">
      <input id="txtCell" class="txt" placeholder="Cell Phone" />
    </td>
    <td class="cellContent">
      <input id="txtLandline" class="txt" placeholder="Landline" />
    </td>
  </tr>

  <tr>
    <td colspan="3" style="text-align: right">
      <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button>
    </td>
  </tr>
</table>



