Skip to content
Advertisement

Display table on button click in Javascript

I am building a sample project named: Tennis Club Management using javascript, HTML, CSS, bootstrap. In this i have a Login Page (index.html) and Manage Players Page (managePlayers.html). In managePlayers.html, I have two buttons namely Add Player and Show Players. On click events of the two buttons, I need to show the tables.

Add Players click will show the table created in HTML and Show Players click will show table created in javascript as it will dynamically display table data based on the data fetched from API.

The Problem I am facing is when I click Show Player button the table gets displayed, and after that when I click Add Player button, the table does not show up.

Below are the code files and screenshots:

index.html

// --------------TESTING CODE FOR LOGIN PAGE LOGIN BUTTON CLICK----------------

var istableCreated = false;
var email, password,IDvalue=0;
document.querySelector(".loginbtn").addEventListener("click", (e) => {
    email = document.querySelector(".email").value;
    password = document.querySelector(".password").value;

    document.querySelector(".labelemailerror").innerHTML = "";
    document.querySelector(".labelpassworderror").innerHTML = "";

    // ------------TESTING CODE FOR CHECKING VALIDATION AND PRINTING ERROR ON LABELS IF ANY-------------

    if (email === "admin@wimbledon.com" && password === "rogerfederer") {
        console.log("Login successfull....");
        window.open("profile.html");
    }
    else if (email === "" && password === "") {

        document.querySelector(".labelpassworderror").innerHTML = "Email and Password cannot be blank"
    }
    else if (email === "") {

        document.querySelector(".labelemailerror").innerHTML = "Email cannot be blank";
    }
    else if (password === "") {

        document.querySelector(".labelpassworderror").innerHTML = "Password cannot be blank"
    }
    else {

        document.querySelector(".labelpassworderror").innerHTML = "Invalid Email or Password";
    }

    console.log(email, password);
    e.preventDefault();
});





//------------------------------------MANAGE PLAYERS PAGE----------------------------------

//--------------------------------TESTING CODE FOR SHOWING PLAYERS OF MANAGE PLAYERS PAGE--------------------------
function showplayers() {
    document.querySelector(".customerregistration").innerHTML="";

    if (istableCreated == false) {


        istableCreated = true;
        console.log(istableCreated);

        //----------TESTING CODE FOR CREATING WRAPPER FOR BOOTSTRAP TABLE FOR RESPONSIVENESS--------

        var myDiv = document.createElement("div");
        myDiv.className = "table-responsive";
        myDiv.id = "table-responsive";
        myDiv.style.display="inline-block";
        document.body.appendChild(myDiv);

        //-----------TESTING CODE FOR CREATING BOOTSTRAP DYNAMIC TABLE USING JAVASCRIPT-------------

        var myTable = document.createElement("table");
        myTable.style.marginTop = "2%";
        myTable.className = "table";
        myTable.id = "table";
        document.body.appendChild(myDiv).appendChild(myTable);


        var myThead = document.createElement("thead");
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead);

        var myTr = document.createElement("tr");
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr);

        var myThID = document.createElement("th");
        myThID.scope = "col";
        myThID.innerHTML = "ID";
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThID);

        var myThName = document.createElement("th");
        myThName.scope = "col";
        myThName.innerHTML = "Name";
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThName);

        var myThGender = document.createElement("th");

        myThGender.scope = "col";
        myThGender.innerHTML = "Gender";
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThGender);

        var mySubscription = document.createElement("th");
        mySubscription.scope = "col";
        mySubscription.innerHTML = "Subscription";
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(mySubscription);

        var myfeeStatus = document.createElement("th");
        myfeeStatus.scope = "col";
        myfeeStatus.innerHTML = "Fee Status";
        document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myfeeStatus);

    }
    else {
        console.log(istableCreated);
    }
}



//---------------------TESTING CODE FOR DISPLAYING TABLE FOR ADDING CUSTOMER INFORMATION--------------- 


function addplayers() {
    console.log("add players clicked.....");
    document.querySelector(".customerregistration").style.display = "block";
    IDvalue+=1;
    // document.querySelector(".ID").value=IDvalue;

}



//--------------------------TESTING CODE FOR SAVING CUSTOMER INFORMATION OF MANAGE PLAYERS PAGE-----------------------------



function save() {
    console.log("data saved successfully...");
    return false;
}

managePlayers.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Players</title>

    <!-- ADDING FONT AWESOME CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <!-- ADDING BOOTSTRAP CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <!-- ADDING STYLE.CSS -->
    <link rel="stylesheet" href="/css/style.css">

</head>

<body class="managePlayers">

    <!-- ADDING BUTTONS LIKE SHOW PLAYERS, ADD PLAYERS USING CSS BOOTSTRAP -->
    <button type="button" class="btn btn-secondary showplayers" onclick="showplayers();">Show Players</button>
    <button type="button" class="btn btn-secondary addplayers" onclick="addplayers()">Add Players</button>

    <!-- CREATING REGISTRATION FORM OF CUSTOMER -->
    <table class="customerregistration">
        <tr>
            <td>
                <Label>ID :</Label>
            </td>
            <td>
                <input type="text" class ="ID" readonly>
            </td>
        </tr>
        <tr>
            <td>
                <label>DOB :</label>
            </td>
            <td>
                <input type="date" id="birthday" name="birthday">
            </td>
        </tr>
        <tr>
            <td>
                <label>NAME :</label>
            </td>
            <td>
                <input type="text" class="name" id="name">
            </td>
        </tr>

        <tr>
            <td>
                <label>GENDER :</label>
            </td>
            <td>
                <input type="radio" name="gender" value="female"> Female
                <input type="radio" name="gender" value="male"> Male
            </td>
            
        </tr>

        <tr>
            <td>
                <label>CONTACT :</label>
            </td>
            <td>
                <input type="text" class="customercontact" id="customercontact">
            </td>
        </tr>
        
        <tr>
            <td>
                <label>ADDRESS :</label>
            </td>
            <td>
                <textarea class="address" id="address" cols="20" rows="3"></textarea>
            </td>
        </tr>

        <tr>
            <td>
                <label>ID PROOF :</label>
                <select class="idproof" id="idproof">
                    <option value="select">---Select---</option>
                    <option value="license">License</option>
                    <option value="aadhaar">Aadhaar</option>
                    <option value="passport">Passport</option>
                </select>
            </td>
            <td>
                <input type="text" class="idprooftextbox">
            </td>
        </tr>

        <tr>
            <td>
                <label>MEMBERSHIP FOR :</label>
            </td>
            <td>
                <select class="membershipfor" id="membershipfor">
                    <option value="select">---Select---</option>
                    <option value="court">COURT</option>
                    <option value="tournament">TOURNAMENT</option>
                    <option value="both">BOTH</option>
                </select>
            </td>
        </tr>

        <tr>
            <td>
                <label>MEMBERSHIP TYPE :</label>
            </td>
            <td>
                <select class="membershiptype" id="membershiptype">
                    <option value="select">---Select---</option>
                    <option value="monthly">MONTHLY</option>
                    <option value="halfyearly">HALF YEARLY</option>
                    <option value="annually">ANNUALLY</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <button type="button" class="btn btn-success save">SAVE</button>
            </td>
        </tr>
    </table>

    <!-- ADDING BOOTSTRAP JS -->
    <!-- JS, Popper.js, and jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous"></script>

    <!-- ADDING INDEX.JS -->
    <script src="/js/sidebar.js"></script>
    <script src="/js/index.js"></script>

</body>

</html>

Screenshots

Table show on show players click

Nothin happens when I click on Add players

No table display

Any Solution please ?

https://jsfiddle.net/mohitsharma1991/s2ncwqvL/1/

Advertisement

Answer

You need to use the tbody with id selector and hide add Player section if the show players is clicked or vise versa when the show players is clicked you need to set the add players to display:none

The reason it was not working with your existing code was that you were using innerHTML and clearing it out completely from the DOM when you click showplayers().

Once you were clicking it back again the DOM is cleared with add player section and does not exist anymore.

Live Demo:

// --------------TESTING CODE FOR LOGIN PAGE LOGIN BUTTON CLICK----------------

var istableCreated = false;
var email, password, IDvalue = 0;
/* document.querySelector(".loginbtn").addEventListener("click", (e) => {
  email = document.querySelector(".email").value;
  password = document.querySelector(".password").value;

  document.querySelector(".labelemailerror").innerHTML = "";
  document.querySelector(".labelpassworderror").innerHTML = "";

  // ------------TESTING CODE FOR CHECKING VALIDATION AND PRINTING ERROR ON LABELS IF ANY-------------

  if (email === "admin@wimbledon.com" && password === "rogerfederer") {
    console.log("Login successfull....");
    window.open("profile.html");
  } else if (email === "" && password === "") {

    document.querySelector(".labelpassworderror").innerHTML = "Email and Password cannot be blank"
  } else if (email === "") {

    document.querySelector(".labelemailerror").innerHTML = "Email cannot be blank";
  } else if (password === "") {

    document.querySelector(".labelpassworderror").innerHTML = "Password cannot be blank"
  } else {

    document.querySelector(".labelpassworderror").innerHTML = "Invalid Email or Password";
  }

  console.log(email, password);
  e.preventDefault();
});
 */


//------------------------------------MANAGE PLAYERS PAGE----------------------------------

//--------------------------------TESTING CODE FOR SHOWING PLAYERS OF MANAGE PLAYERS PAGE--------------------------
function showplayers() {
  // document.querySelector(".customerregistration").innerHTML = "";
  document.querySelector("#add_player").style.display = "none";

  if (istableCreated == false) {
    istableCreated = true;

    //----------TESTING CODE FOR CREATING WRAPPER FOR BOOTSTRAP TABLE FOR RESPONSIVENESS--------

    var myDiv = document.createElement("div");
    myDiv.className = "table-responsive";
    myDiv.id = "table-responsive";
    myDiv.style.display = "inline-block";
    document.body.appendChild(myDiv);

    //-----------TESTING CODE FOR CREATING BOOTSTRAP DYNAMIC TABLE USING JAVASCRIPT-------------

    var myTable = document.createElement("table");
    myTable.style.marginTop = "2%";
    myTable.className = "table";
    myTable.id = "table";
    document.body.appendChild(myDiv).appendChild(myTable);


    var myThead = document.createElement("thead");
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead);

    var myTr = document.createElement("tr");
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr);

    var myThID = document.createElement("th");
    myThID.scope = "col";
    myThID.innerHTML = "ID";
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThID);

    var myThName = document.createElement("th");
    myThName.scope = "col";
    myThName.innerHTML = "Name";
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThName);

    var myThGender = document.createElement("th");

    myThGender.scope = "col";
    myThGender.innerHTML = "Gender";
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThGender);

    var mySubscription = document.createElement("th");
    mySubscription.scope = "col";
    mySubscription.innerHTML = "Subscription";
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(mySubscription);

    var myfeeStatus = document.createElement("th");
    myfeeStatus.scope = "col";
    myfeeStatus.innerHTML = "Fee Status";
    document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myfeeStatus);

  } else {
    document.querySelector("#table-responsive").style.display = "block";
  }
}



//---------------------TESTING CODE FOR DISPLAYING TABLE FOR ADDING CUSTOMER INFORMATION--------------- 


function addplayers() {
  document.querySelector("#add_player").style.display = "block";
  if (istableCreated) {
    document.querySelector("#table-responsive").style.display = "none";
  }

  IDvalue += 1;
  // document.querySelector(".ID").value=IDvalue;
}



//--------------------------TESTING CODE FOR SAVING CUSTOMER INFORMATION OF MANAGE PLAYERS PAGE-----------------------------



function save() {
  console.log("data saved successfully...");
  return false;
}
form {
  margin: auto;
  /* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
  width: 30%;
}

img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 25%;
  height: 25%;
  margin-top: 3%;
  margin-bottom: 1.5%;
}

.login {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

label {
  font-weight: bolder;
}

.labelemailpassworderror {
  color: red;
  font-size: 10px;
  text-align: left;
}

.labelemailerror {
  color: red;
  font-size: 10px;
  text-align: center;
}

.labelpassworderror {
  color: red;
  font-size: 10px;
  text-align: center;
}

h3 {
  text-align: center;
}

h5 {
  text-align: center;
  color: green;
}

.forgotpassword {
  text-align: center;
  font-size: 10px;
  /* margin-left: 25%; */
}

.signup {
  text-align: center;
  font-size: 10px;
}

span {
  color: #1a73e8;
}

span:hover {
  color: purple;
}


/* ---------------- SETTING CSS PROPERTIES OF PROFILE PAGE---------------- */

body {
  margin-top: 0;
  font-family: "Lato", sans-serif;
}

.sidebar {
  top: 0;
  left: 0;
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
}

.sidebar a.active {
  background-color: #4CAF50;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

div.content {
  margin-left: 200px;
  padding: 1px 16px;
  height: 1000px;
}

@media screen and (max-width: 700px) {
  .sidebar {
    width: 100%;
    height: auto;
    position: relative;
  }

  .sidebar a {
    float: left;
  }

  div.content {
    margin-left: 0;
  }
}

@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}

.editadminprofile {
  float: right;
}


/* ---------------- SETTING CSS PROPERTIES OF MANAGE PLAYERS PAGE---------------- */

.showplayers {
  margin-right: 30%;
  margin-top: 5%;
  margin-bottom: 2%;
  float: right;
  width: 15%;
}

.addplayers {
  margin-right: 3%;
  margin-top: 5%;
  margin-bottom: 2%;
  float: right;
  width: 15%;
}


/* ---------------- SETTING CSS PROPERTIES OF MANAGE TRAINERS PAGE---------------- */

.showtrainers {
  margin-right: 30%;
  margin-top: 5%;
  float: right;
  width: 15%;
}

.addtrainers {
  margin-right: 3%;
  margin-top: 5%;
  float: right;
  width: 15%;
}


/* ---------------- SETTING CSS PROPERTIES OF MANAGE TOURNAMENTS PAGE---------------- */

.showtournaments {
  margin-right: 30%;
  margin-top: 5%;
  float: right;
  width: 15%;
}

.addtournaments {
  margin-right: 3%;
  margin-top: 5%;
  float: right;
  width: 15%;
}


/* ---------------- SETTING CSS PROPERTIES OF MANAGE MATCHES PAGE---------------- */

.showmatches {
  margin-right: 30%;
  margin-top: 5%;
  float: right;
  width: 15%;
}

.addmatches {
  margin-right: 3%;
  margin-top: 5%;
  float: right;
  width: 15%;
}


/* ---------------- SETTING CSS PROPERTIES OF MANAGE FEES PAGE---------------- */

.showfees {
  margin-right: 30%;
  margin-top: 5%;
  float: right;
  width: 15%;
}

.addfees {
  margin-right: 3%;
  margin-top: 5%;
  float: right;
  width: 15%;
}


/* ---------------- SETTING CSS PROPERTIES OF TABLE OF MANAGE PLAYER PAGE ---------------- */

table {
  table-layout: fixed;
}

table th,
table td {
  overflow: hidden;
}

th {
  width: 5%;
}


/*-------------- SETING CSS PROPERTIES OF CUSTOMER REGISTRATION FORM-------------*/

.customerregistration {
  margin-top: 5%;
  float: right;
  margin-right: 32%;
}

#add_player {
  display: none;
}

td {
  padding: 1.4%;
}

.address {
  resize: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Manage Players</title>

  <!-- ADDING FONT AWESOME CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

  <!-- ADDING BOOTSTRAP CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  <!-- ADDING STYLE.CSS -->
  <link rel="stylesheet" href="/css/style.css">

</head>

<body class="managePlayers">

  <!-- ADDING BUTTONS LIKE SHOW PLAYERS, ADD PLAYERS USING CSS BOOTSTRAP -->
  <button type="button" class="btn btn-secondary showplayers" onclick="showplayers();">Show Players</button>
  <button type="button" class="btn btn-secondary addplayers" onclick="addplayers()">Add Players</button>

  <!-- CREATING REGISTRATION FORM OF CUSTOMER -->
  <table class="customerregistration">
    <tbody id="add_player">
      <tr>
        <td>
          <Label>ID :</Label>
        </td>
        <td>
          <input type="text" class="ID" readonly>
        </td>
      </tr>
      <tr>
        <td>
          <label>DOB :</label>
        </td>
        <td>
          <input type="date" id="birthday" name="birthday">
        </td>
      </tr>
      <tr>
        <td>
          <label>NAME :</label>
        </td>
        <td>
          <input type="text" class="name" id="name">
        </td>
      </tr>

      <tr>
        <td>
          <label>GENDER :</label>
        </td>
        <td>
          <input type="radio" name="gender" value="female"> Female
          <input type="radio" name="gender" value="male"> Male
        </td>

      </tr>

      <tr>
        <td>
          <label>CONTACT :</label>
        </td>
        <td>
          <input type="text" class="customercontact" id="customercontact">
        </td>
      </tr>

      <tr>
        <td>
          <label>ADDRESS :</label>
        </td>
        <td>
          <textarea class="address" id="address" cols="20" rows="3"></textarea>
        </td>
      </tr>

      <tr>
        <td>
          <label>ID PROOF :</label>
          <select class="idproof" id="idproof">
            <option value="select">---Select---</option>
            <option value="license">License</option>
            <option value="aadhaar">Aadhaar</option>
            <option value="passport">Passport</option>
          </select>
        </td>
        <td>
          <input type="text" class="idprooftextbox">
        </td>
      </tr>

      <tr>
        <td>
          <label>MEMBERSHIP FOR :</label>
        </td>
        <td>
          <select class="membershipfor" id="membershipfor">
            <option value="select">---Select---</option>
            <option value="court">COURT</option>
            <option value="tournament">TOURNAMENT</option>
            <option value="both">BOTH</option>
          </select>
        </td>
      </tr>

      <tr>
        <td>
          <label>MEMBERSHIP TYPE :</label>
        </td>
        <td>
          <select class="membershiptype" id="membershiptype">
            <option value="select">---Select---</option>
            <option value="monthly">MONTHLY</option>
            <option value="halfyearly">HALF YEARLY</option>
            <option value="annually">ANNUALLY</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>
          <button type="button" class="btn btn-success save">SAVE</button>
        </td>
      </tr>
    </tbody>
  </table>

  <!-- ADDING BOOTSTRAP JS -->
  <!-- JS, Popper.js, and jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

</body>

</html>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement