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
Nothin happens when I click on Add players
Any Solution please ?
https://jsfiddle.net/mohitsharma1991/s2ncwqvL/1/
You should change the ID of your input to another ID, and then your function just need to be as below.
function myfunction()
{
if (document.getElementById("displaytable").style.display === "none")
document.getElementById("displaytable").style.display="block";
else
document.getElementById("displaytable").style.display="none";
}
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>
In you showPlayers() method you used document.querySelector(".customerregistration").innerHTML=""; and because of which you Add Player form has been completely removed. so, instead of using innerHTML = ''; use something like this
document.querySelector('.customerrrgistration').style.display = "none"; and when you wanna display it use this document.querySelector('.customerrrgistration').style.display = "block";
// --------------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>
Related
I want a table (table1) to be displayed n times according the number entered by the user in the input form. Then for each instance of this table the user should be able to click on each row and another relevant table should be displayed.
So far I can produce table1 n times according to user input. But then the function myFunction_disease is only applying to the first iteration of table1. I want each copy of table1 to controlled independently depending on what the user clicks.
Here is jsfiddle: https://jsfiddle.net/k0x4y6d2/1/
<div class="user_input_outer" id="num_of_conditions">
<div class= "content_text"> Number of conditions:</div>
<div class="user_input">
<input type="number" id="numb_conditions" onchange="myFunction_num_conditions();" min="2" max="1"> </div>
</div>
<div id=condition_detail>
</div>
function myFunction_num_conditions(x) {
container = document.getElementById('numb_conditions')
var number = container.value
for (var i = 0; i < number; i++) {
count = i+1
document.getElementById("condition_detail").innerHTML += 'Condition' + (i + 1);
let newdiv = document.createElement('div');
newdiv.innerHTML = "<table id=table1 class=table> <tr onclick='myFunction_disease(this)'><td>cardiac </td></tr> <tr onclick='myFunction_disease(this)'><td> respiratory </td></tr> <tr onclick='myFunction_disease(this)'><td>infection</td></tr></table><table id=table2 class=table> <tr onclick='myFunction_cardiac(this)'><td>MI </td></tr> <tr onclick='myFunction_cardiac(this)'> <td> valve disease </td></tr> <tr 'myFunction_cardiac(this)'><td>CCF</td></tr></table> <table id=table3 class=table> <tr onclick='myFunction_respiratory(this)'><td>COPD </td></tr> <tr onclick='myFunction_respiratory(this)'><td> asthma </td></tr> <tr onclick='myFunction_respiratory(this)'><td>bronchiectasis</td></tr></table><table id=table4 class=table> <tr onclick='myFunction_infectious(this)'><td>TB </td></tr> <tr onclick='myFunction_infectious(this)'><td> pneumonia </td></tr> <tr onclick='myFunction_infectious(this)'><td>cellulitis</td></tr></table>"
document.getElementById('condition_detail').appendChild(newdiv);
}
}
function myFunction_disease(x) {
const disease = document.querySelector("#table1");
const cardiac = document.querySelector("#table2");
const respiratory = document.querySelector("#table3");
const infectious = document.querySelector("#table4");
if (x.rowIndex== 0){
cardiac.style.display= "table"
respiratory.style.display= "none"
infectious.style.display = "none"
}
else if (x.rowIndex== 1){
cardiac.style.display= "none"
respiratory.style.display= "table"
infectious.style.display = "none"
}
else if (x.rowIndex== 2){
cardiac.style.display= "none"
respiratory.style.display= "none"
infectious.style.display = "table"
}
}
div.user_input {
display: table-cell;
width: 150px;
font-family: sans-serif;
font-size: 12;
line-height: 10px;
}
div.user_input > input {
width: 140px;
margin: 0px;
padding: 0px;
font-family: sans-serif;
font-size: 14;
line-height: 19px;
}
.user_input:focus {
outline: 0 !important;
}
.table {
margin: 25px 0;
font-size: 13;
font-family: sans-serif;
min-width: 200px;
margin-left: auto;
margin-right: auto;
width: 25%;
border-style: solid;
border-width: 1px;
}
.table td{
margin: 25px 0;
font-size: 13;
font-family: sans-serif;
min-width: 200px;
margin-left: auto;
margin-right: auto;
width: 25%;
border-style: solid;
border-width: 1px;
}
#table2 {
display: none;
}
#table3 {
display: none;
}
#table4 {
display: none;
}
That's what you need. For adding more buttons and tables you can just simply add a new table and give a new class table$ (where $ is number, example: table4) and add a new button with data-table-show=$ attribute. That's all😉.
// Creating conditions
const numInput = document.getElementById('num'),
conditionForm = document.getElementById('condition-form'),
tablesContainer = document.getElementById('tables'),
conditionText = tablesContainer.innerHTML;
conditionForm.onsubmit = async function(e) {
e.preventDefault();
const numValue = Number(numInput.value);
await (tablesContainer.innerHTML += conditionText.repeat(numValue));
addEventListenersToButtons();
}
// Working with table filtering
function addEventListenersToButtons() {
let buttons = document.querySelectorAll('#tables tr.btn');
buttons.forEach(function(button, i) {
button.onclick = function() {
const tables = button.parentNode.parentNode.parentNode.querySelectorAll('.data-table');
tables.forEach(table => {
if (table.classList.contains(`table${button.dataset.tableShow}`)) {
table.classList.remove('hide')
} else {
table.classList.add('hide')
}
});
}
})
}
addEventListenersToButtons();
.tables-group table {
margin: 25px 0;
font-size: 13;
font-family: sans-serif;
min-width: 200px;
margin-left: auto;
margin-right: auto;
width: 25%;
border-style: solid;
border-width: 1px;
}
.tables-group table td {
margin: 25px 0;
font-size: 13;
font-family: sans-serif;
min-width: 200px;
margin-left: auto;
margin-right: auto;
width: 25%;
border-style: solid;
border-width: 1px;
}
.data-table.hide {
display: none;
}
<div class="container">
<form id="condition-form">
<label for="num">Number of conditions</label>
<input type="number" name="conditions" id="num" min="0">
<button type="submit" name="conditions">Submit</button>
</form>
<hr>
<div id="tables">
<div class="condition">
<div class="tables-group">
<table>
<tr class="btn cardiac" data-table-show="1">
<td>cardiac</td>
</tr>
<tr class="btn respiratory" data-table-show="2">
<td>respiratory</td>
</tr>
<tr class="btn infection" data-table-show="3">
<td>infection</td>
</tr>
</table>
<table class="data-table table1 hide">
<tr>
<td>MI</td>
</tr>
<tr>
<td>valve disease</td>
</tr>
<tr 'myFunction_cardiac(this)'>
<td>CCF</td>
</tr>
</table>
<table class="data-table table2 hide">
<tr>
<td>COPD</td>
</tr>
<tr>
<td>asthma</td>
</tr>
<tr>
<td>bronchiectasis</td>
</tr>
</table>
<table class="data-table table3 hide">
<tr>
<td>TB</td>
</tr>
<tr>
<td>pneumonia</td>
</tr>
<tr>
<td>cellulitis</td>
</tr>
</table>
</div>
</div>
</div>
</div>
Adding new info input changes the previous modal contents.
$(document).ready(function() {
$('#mainTable').DataTable({});
var dataTable = $("#mainTable").dataTable().api();
$("#add").click(function() {
var fname = $('#fname').val();
lname = $('#lname').val();
var info = $('.info').val();
tr = document.createElement("tr");
tr.innerHTML = "<tr><td>" + fname + "</td><td>" + lname + "</td><td><div><button id='showInfo' class='showInfo' type='button'>+</button></div></td></tr>";
dataTable.row.add(tr);
dataTable.draw();
$(document).on("click", '.showInfo', function() {
$('.modalinfo').text(info);
$(".modal").css("display", "block");
});
$(".close").click(function() {
$(".modal").css("display", "none");
});
});
});
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
Result Size: 753 x 671
color: #000;
text-decoration: none;
cursor: pointer;
}
<head>
<link rel="stylesheet" type="text/css" href="{% static '//cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css' %}">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div id="inputlines">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" onfocus="this.value=''" id="fname"></td>
<td>Last Name:</td>
<td><input type="text" onfocus="this.value=''" id="lname"></td>
<td>Info:</td>
<td><input type="text" onfocus="this.value=''" id="info" class="info"></td>
<td><input type="button" id="add" value="Add"></td>
</tr>
</table>
</div>
<table id="mainTable">
<thead id="myTableData">
<tr>
<th><b>First Name</b></th>
<th><b>Last Name</b></th>
<th> </th>
</tr>
</thead>
<tfoot>
</tfoot>
<tbody>
</tbody>
</table>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p class="modalinfo"></p>
</div>
</div>
<input type="button" id="showInfo" class='showInfo' style="display:none;">
</body>
https://jsfiddle.net/averola/b4p0zu6q/3/
The issue is because you add a new event to every pre-existing .showInfo element when a new one is added to the DOM. This overwrites the info value with the latest one for each instace.
To fix this you could add the info value as a data attribute on each new button you append, and this can then be read back out of the DOM in a single delegated event handler which applies to all buttons. Try this:
$(document).ready(function() {
$('#mainTable').DataTable({});
var dataTable = $("#mainTable").dataTable().api();
$("#add").click(function() {
let fname = $('#fname').val();
let lname = $('#lname').val();
let info = $('.info').val();
let $tr = $(`<tr><td>${fname}</td><td>${lname}</td><td><div><button class="showInfo" type="button" data-info="${info}">+</button></div></td></tr>`);
dataTable.row.add($tr);
dataTable.draw();
});
$(document).on("click", '.showInfo', function() {
$('.modalinfo').text($(this).data('info'));
$(".modal").css("display", "block");
});
$(".close").click(function() {
$(".modal").css("display", "none");
});
});
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<link rel="stylesheet" type="text/css" href="{% static '//cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css' %}">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<div id="inputlines">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" onfocus="this.value=''" id="fname"></td>
<td>Last Name:</td>
<td><input type="text" onfocus="this.value=''" id="lname"></td>
<td>Info:</td>
<td><input type="text" onfocus="this.value=''" id="info" class="info"></td>
<td><input type="button" id="add" value="Add"></td>
</tr>
</table>
</div>
<table id="mainTable">
<thead id="myTableData">
<tr>
<th><b>First Name</b></th>
<th><b>Last Name</b></th>
<th> </th>
</tr>
</thead>
<tfoot>
</tfoot>
<tbody>
</tbody>
</table>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p class="modalinfo"></p>
</div>
</div>
<input type="button" id="showInfo" class='showInfo' style="display:none;">
im trying to make a average grade calculator, now thats is going fine but now i want to add a row of inputs every time you click on a button, including html, javascript and also the assigned numbers increased by one. The inputs should go just under the existing ones and the calculate button should move along. I've been stuck at this point for a view days now, appreciate the help!
function getValue(el){
return (+document.getElementById(el).value)
};
function calculator() {
var weight1=getValue('weight-1');
var mark1=getValue('mark-1');
var grade1=weight1*mark1;
var weight2=getValue('weight-2');
var mark2=getValue('mark-2');
var grade2=weight2*mark2;
var totalWeight=weight1+weight2;
var totalGrade=grade1+grade2;
var finalGrade=totalGrade/totalWeight;
var display=document.getElementById('outputDiv');
display.innerHTML='Je gemiddelde is: ' +finalGrade.toFixed(2);
}
body {
font-family: 'Roboto', sans-serif;
background-color: ;
}
h2, h3 {
text-align: center;
}
table {
margin: auto;
}
#table-title {
font-size: 20px;
font-style: italic;
text-align: center;
position: relative;
}
#weight-1, #weight-2 {
width: 100px;
}
input {
text-align: center;
}
#button-div {
position: relative;
width: 150px;
margin: auto;
}
#calc-button {
position: relative;
padding: 5px;
margin-top: 20px;
}
#calc-button:hover {
border-color: black;
box-shadow: 8px 8px 8px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
#outputDiv {
height: 50px;
text-align: center;
width: 300px;
margin: auto;
margin-top: 20px;
}
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<header>
<h2>Gemiddelde cijfer</h2>
<h3>Voer hieronder je cijfers in</h3>
</header>
<body>
<table id="table">
<tr id="table-title">
<td>Weging</td>
<td>Cijfer</td>
</tr>
<tr>
<td><input id="weight-1" type="text" size=2 maxlength="5" value=""></td>
<td><input id="mark-1" type="text" size=2 maxlength="5" value=""></td>
</tr>
<tr>
<td><input id="weight-2" type="text" size=2 maxlength="5" value=""></td>
<td><input id="mark-2" type="text" size=2 maxlength="5" value=""></td>
</tr>
</table>
<div id="button-div">
<input id="calc-button" type="button" value="Berekenen je gemiddelde" onclick="calculator()">
</div>
<div id="outputDiv"></div>
</body>
</html>
Instead of hard coding the ids of your inputs, you can get your weight and mark inputs with querySelectoryAll this will get you all your inputs no matter how many there are and then you can loop over the elements to get the values and then append a new input row with the id incremented by 1 to the tbody. Then the next time you call the function there will be one more input to loop over Here's an example based on your code:
function calculator() {
var weight = 0;
var mark = 0;
var weights = document.querySelectorAll('[id^=weight-]');
var grades = document.querySelectorAll('[id^=mark-]');
var trs = document.getElementsByTagName('tr');
var tBody = document.getElementsByTagName('tbody')[0];
var totalWeight = 0;
var totalGrade = 0;
for (var i = 0; i < weights.length; i++) {
totalWeight += +weights[i].value;
}
for (var i = 0; i < grades.length; i++) {
totalGrade += +grades[i].value;
}
var finalGrade=totalGrade/totalWeight;
var display = document.getElementById('outputDiv');
var newTr = document.createElement('TR');
newTr.innerHTML = `<td><input id="weight-${trs.length + 1}" type="text" size=2 maxlength="5" value=""></td><td><input id="mark-${trs.length + 1}" type="text" size=2 maxlength="5" value=""></td>`
tBody.appendChild(newTr);
display.innerHTML='Je gemiddelde is: ' +finalGrade.toFixed(2);
}
body {
font-family: 'Roboto', sans-serif;
background-color: ;
}
h2, h3 {
text-align: center;
}
table {
margin: auto;
}
#table-title {
font-size: 20px;
font-style: italic;
text-align: center;
position: relative;
}
[id^="weight-"] {
width: 100px;
}
input {
text-align: center;
}
#button-div {
position: relative;
width: 150px;
margin: auto;
}
#calc-button {
position: relative;
padding: 5px;
margin-top: 20px;
}
#calc-button:hover {
border-color: black;
box-shadow: 8px 8px 8px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
#outputDiv {
height: 50px;
text-align: center;
width: 300px;
margin: auto;
margin-top: 20px;
}
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<header>
<h2>Gemiddelde cijfer</h2>
<h3>Voer hieronder je cijfers in</h3>
</header>
<body>
<table id="table">
<tr id="table-title">
<td>Weging</td>
<td>Cijfer</td>
</tr>
<tr>
<td><input id="weight-1" type="text" size=2 maxlength="5" value=""></td>
<td><input id="mark-1" type="text" size=2 maxlength="5" value=""></td>
</tr>
<tr>
<td><input id="weight-2" type="text" size=2 maxlength="5" value=""></td>
<td><input id="mark-2" type="text" size=2 maxlength="5" value=""></td>
</tr>
</table>
<div id="button-div">
<input id="calc-button" type="button" value="Berekenen je gemiddelde" onclick="calculator()">
</div>
<div id="outputDiv"></div>
</body>
</html>
regarding your question and as Barmar said, StackOverflow requires the user to at least attempt the problem, when you run into a wall then you can ask away. I can't overrule this so I can't give you the actual code but I did manage to get it working quite quickly, if you understand Javascript it shouldn't be that difficult. I will try to give you hints on how it really should be structured.
Your Javascript needs to append all your form inputs from the beginning, set a variable equal to 0 and just append on button click a new input field onto the id="table" and increment by 1. This is as far as "I" personally can go to but if you show me that you attempted I can most definitively help you from there.
Best of luck!
This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 4 years ago.
Good day!
My form has javascript functions for my buttons for adding rows from table and resetting the text fields in the form itself.
In my add button, I have an incrementing variable, rowCount, for counting the row. It works well and works what I expected. When I put it inside the <form></form> tag, it stuck at 2, doesn't increment and doesn't add rows at all.
Here's my code for our reference and also to be debugged. Thanks in advance!
var rowCount = 1;
function addRow() {
var table = document.getElementById('tblOrder');
rowCount = rowCount + 1;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
cell0.innerHTML = "<input type='text'>";
cell1.innerHTML = "<input type='number'>";
cell2.innerHTML = "<input type='text'>";
cell3.innerHTML = "<input type='text'>";
cell4.innerHTML = "<input type='text'>";
cell5.innerHTML = "<input type='text'>";
alert(rowCount)
}
function resetForm() {
document.getElementById('orderForm').reset();
alert('All cleared!')
}
body {
font-family: Calibri;
font-weight: bold;
}
#main {
width: 90%;
border: 1px solid black;
margin: auto;
position: relative;
padding-bottom: 10px;
}
#mainTitle {
text-align: center;
text-decoration: underline;
/* font-weight: bold; */
font-size: 36px;
margin-top: 20px;
margin-bottom: 20px;
}
#cust, #prod {
width: 90%;
position: relative;
margin: auto;
border: 1px solid black;
padding: 20px;
}
#cust {
margin-bottom: 20px;
}
#prod {
margin-bottom: 10px;
}
#custTitle, #prodTitle {
color: blue;
font-size: 25px;
/* font-weight: bold; */
text-decoration: underline;
margin-bottom: 20px;
/* position: relative; */
}
#cust p {
display: block;
}
#cust input {
display: inline;
}
#right {
position: absolute;
top: 0;
right: 0;
padding: 10px;
/* border: 1px solid black; */
}
#right p {
right: 0;
}
#tblOrder {
width: 100%;
border: 1px solid black;
}
#tblOrder thead {
background-color: darkgreen;
color: white;
font-size: 18px;
}
#tblOrder td {
text-align: center;
padding: 5px;
}
#inp1 {
width: 5%;
}
#inp2 {
width: 10%;
}
#inp3, #inp5, #inp6 {
width: 15%;
}
#inp4 {
width: 40%;
}
#tblOrder tr td input {
width: 95%;
}
#add {
color: blue;
font-weight: bold;
background-color: white;
border: 1px solid white;
margin-top: 10px;
}
#foot {
position: relative;
width: 90%;
margin: auto;
/* border: 1px solid black; */
}
#buttons {
position: relative;
left: 0;
/* display: inline; */
}
#total {
position: absolute;
right: 0;
/* display: inline; */
}
<!DOCTYPE html>
<html>
<head>
<title>Forms</title>
<link type='text/css' rel='stylesheet' href='style.css'>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<div id='main'>
<div id='mainTitle'>
Order Form
</div>
<form id='orderForm'>
<div id='cust'>
<div id='custTitle'>
Customer
</div>
<div id='left'>
<p>Customer Name: <input type='text' size=80></p>
<p>Address: <input type='text' size=100></p>
<p>Contact Name: <input type='text' size=80></p>
<p>Phone: <input type='text' size=15>
Mobile: <input type='text' size=15></p>
<p>E-mail Address: <input type='text' size=30>#<input type='text' size=10>.com</p>
</div>
<div id='right'>
<p>Order Date: <input type='text' placeholder='mm/dd/yyyy' size=11></p>
<p>Order Number: <input type='text' size=5></p>
</div>
</div>
<div id='prod'>
<div id='prodTitle'>
Products to Order
</div>
<div id='order'>
<table id='tblOrder'>
<thead>
<td id='inp1'>Unit</td>
<td id='inp2'>Quantity</td>
<td id='inp3'>Product Code</td>
<td id='inp4'>Description</td>
<td id='inp5'>Unit Price</td>
<td id='inp6'>Total Price</td>
</thead>
<tbody>
<tr>
<td><input type='text'></td>
<td><input type='number'></td>
<td><input type='text'></td>
<td><input type='text'></td>
<td><input type='text'></td>
<td><input type='text'></td>
</tr>
</tbody>
</table>
<button id='add' onclick='addRow()'>+Row</button>
</div>
</div>
<div id='foot'>
<div id='total'>
Total: <input type='text' disabled>
</div>
<div id='buttons'>
<button>Submit</button>
<button onclick='resetForm()'>Reset</button>
</div>
</div>
</form>
</div>
</body>
</html>
If buttons are put inside a form, they become submit buttons by default, meaning they submit the form when clicked. If the form doesn't have an action specified, it will be submitted to the same URL as the page, which results in the page being refreshed. This is what happens in your case.
To prevent a button from submitting the form, set its type to be a generic button instead of a submit button:
<button type="button"></button>
I am new to the development field.
There are two problem with this code.
First when I click button for add_Row then a row gets added on screen but it disappears after 1-2 seconds and same thing happens with group_Create() popup.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Inventory Expert</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../../Bootstrap-3.3.2-dist/css/bootstrap.min.css"/>
<link rel="stylesheet" href="../../CSS/ProductMaster/ProductMaster.css"/>
<link rel="stylesheet" href="../../CSS/ProductMaster/RawMaterialGroup.css"/>
<script src="../../JAVASCRIPT/ProductMaster/ProductMaster.js"></script>
<script src="../../JAVASCRIPT/ProductMaster/RawMaterialGroup.js"></script>
<script src="../../jquery-1.11.2.js"></script>
<script src="../../jquery-ui-1.11.2.custom/jquery-ui.js"></script>
<script src="../../jquery-ui-1.11.2.custom/jquery-ui.min.js"></script>
</head>
<body>
<img id="top" src="../../Images/shaddow_line_top.png" alt=""/>
<div class="container">
<h1><a>Product Master</a></h1>
<form id="productmasterForm">
<table class="table" id="productmasterTable">
<tr>
<td class="W45">Product Code <input id="productid" type="text"/></td>
<td class="W45">Product Name <input id="productname" type="text"/></td>
<td class="W10"></td>
</tr>
<tr>
<td class="W45">Basic Raw Material <input id="basicraw" type="text"/></td>
<td class="W45">Group Name <input id="groupname" type="text"/></td>
<td class="W10">
<div class="btn-group">
<button class="btn btn-info btn-sm" id="groupcreate" onclick="group_Create()">C</button>
<button class="btn btn-info btn-sm" id="groupedit" onclick="group_Edit()">E</button>
</div>
</td>
</tr>
<tr>
<td class="W40">Raw Material <input id="rm1" type="text"/></td>
<td class="W30">Size <input id="s1" type="text"/></td>
<td class="W20">Qty. <input id="q1" type="text"/></td>
<td class="W10">
<div class="btn-group">
<button class="btn btn-info btn-sm" onclick="maprawNsize()">C</button>
<button class="btn btn-info btn-sm" onclick="maprawNsize_Edit()">E</button>
<button class="btn btn-info btn-sm" id="pma" onclick="add_Row()">A</button>
</div>
</td>
</tr>
<tr>
<td class="W45">VAT Rate <input id="vat" type="text"/></td>
<td class="W45">Unit Of Measure <input id="uom" type="text"/></td>
<td class="W10"></td>
</tr>
<tr>
<td class="W45">Manufacturing Cost <input id="menucost" type="text"/></td>
<td class="W45">Sale Rate <input id="salerate" type="text"/></td>
<td class="W10"></td>
</tr>
<tr>
<td class="W45">Maximum Retail Price <input id="mrp" type="text"/></td>
<td class="W45">Default Discount <input id="defdisc" type="text"/></td>
<td class="W10"></td>
</tr>
<tr>
<td class="W45">Rate List Date <input id="listdate" type="text"/></td>
<td class="W45">Kit Reference <input id="kitref" type="text"/></td>
<td class="W10"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
JavaScript File ProductMaster.js
var rowCount = 1;
var rowPosition = 3;
var id = 2;
function add_Row() {
if (rowCount < 11) {
var table = document.getElementById("productmasterTable");
var row = table.insertRow(rowPosition);
rowPosition++;
for (i = 0; i < 1; i++) {
var td1 = document.createElement("td");
td1.innerHTML = 'Raw Material <input id="rm' + id + '" type="text"/>';
row.appendChild(td1);
td1.setAttribute("class", "W40");
}
for (i = 0; i < 1; i++) {
var td2 = document.createElement("td");
td2.innerHTML = 'Size <input id="s' + id + '" type="text"/>';
row.appendChild(td2);
td2.setAttribute("class", "W30");
}
for (i = 0; i < 1; i++) {
var td3 = document.createElement("td");
td3.innerHTML = 'Qty. <input id="q' + id + '" type="text"/>';
row.appendChild(td3);
td3.setAttribute("class", "W20");
}
id++;
rowCount++;
}
else {
alert("Only 10 Allowed");
}
}
JavaScript File RawMaterialGroup.js
function group_Create(){
document.getElementById('rawgroup').style.display = "block";
}
function group_Hide(){
document.getElementById('rawgroup').style.display = "none";
}
function group_Edit(){
alert("I Am Clicked");
}
var rowCount = 5;
var rowPosition = 7;
var id = 2;
function add_rawMaterial() {
if (rowCount < 16) {
var table = document.getElementById("groupTable");
var row = table.insertRow(rowPosition);
rowPosition++;
for (i = 0; i < 1; i++) {
var td1 = document.createElement("td");
td1.innerHTML = 'Raw Material <input id="rmgrm' + id + '" type="text"/>';
row.appendChild(td1);
td1.setAttribute("class", "W40");
}
for (i = 0; i < 1; i++) {
var td2 = document.createElement("td");
td2.innerHTML = 'Qty. <input id="rmgq' + id + '" type="text"/>';
row.appendChild(td2);
td2.setAttribute("class", "W20");
}
for (i = 0; i < 1; i++) {
var td3 = document.createElement("td");
td3.innerHTML = 'UOM <input id="rmguom' + id + '" type="text"/>';
row.appendChild(td3);
td3.setAttribute("class", "W20");
}
id++;
rowCount++;
}
else {
alert("Only 15 Allowed");
}
}
CSS File ProductMaster.css
body{
text-align: center;
overflow: hidden;
}
td{
float: left;
text-align: left
}
#rm1,#rm2,#rm3,#rm4,#rm5,#rm6,#rm7,#rm8,#rm9,#rm10{
width: 250px;
height: 30px
}
#s1,#s2,#s3,#s4,#s5,#s6,#s7,#s8,#s9,#s10{
width: 250px;
height: 30px;
}
#q1,#q2,#q3,#q4,#q5,#q6,#q7,#q8,#q9,#q10{
width: 100px;
height: 30px;
}
.W45{
width: 45%;
}
.W10{
width: 10%;
}
.W15{
width: 15%;
}
.W20{
width: 20%;
}
.W30{
width: 30%;
}
#productid{
width: 100px;
height: 30px;
}
#productname{
width: 300px;
height: 30px;
}
#basicraw{
width: 259px;
height: 30px;
}
#groupname{
width: 315px;
height: 30px;
}
#productmasterForm{
font-size: 20px;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
#vat{
width: 80px;
height: 30px;
}
#uom{
width: 80px;
height: 30px;
}
#menucost{
width: 80px;
height: 30px;
}
#salerate{
width: 80px;
height: 30px;
}
#mrp{
width: 80px;
height: 30px;
}
#defdisc{
width: 80px;
height: 30px;
}
#listdate{
width: 120px;
height: 30px;
}
#kitref{
width: 100px;
height: 30px;
}
CSS File RawMaterialGroup.css
h2 {
background-color:#00a2e2;
padding:20px 20px;
margin:-10px -10px;
text-align:center;
border-radius:10px 10px 0 0;
border: 1px solid #313131;
}
#rawgroup{
width: 100%;
height: 100%;
opacity: 0.95;
top: 0;
bottom: 0;
display: none;
position: fixed;
background-color: #313131;
overflow: hidden;
alignment-adjust: central;
}
div#groupPopup{
position: fixed;
left: 18%;
top: 17%;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
img#close_group{
position: absolute;
right: -7px;
top: -7px;
cursor: pointer;
}
#groupForm{
max-width: 900px;
min-width: 900px;
padding: 10px 10px;
border: 2px solid gray;
border-radius: 10px;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
background-color: #fff;
margin:-10px -11px;
text-align:center;
border-radius:10px 10px 10px 10px;
}
.W40{
width: 40%;
}
.W20{
width: 20%;
}
.W10{
width: 10%;
}
#rmgrm1,#rmgrm2,#rmgrm3,#rmgrm4,#rmgrm5,#rmgrm6,#rmgrm7,#rmgrm8,#rmgrm9,#rmgrm10,#rmgrm11,#rmgrm12,#rmgrm13,#rmgrm14,#rmgrm15{
width: 215px;
height: 30px;
}
#rmgq1,#rmgq2,#rmgq3,#rmgq4,#rmgq5,#rmgq6,#rmgq7,#rmgq8,#rmgq9,#rmgq10,#rmgq11,#rmgq12,#rmgq13,#rmgq14,#rmgq15{
width: 80px;
height: 30px;
}
#rmguom1,#rmguom2,#rmguom3,#rmguom4,#rmguom5,#rmguom6,#rmguom7,#rmguom8,#rmguom9,#rmguom10,#rmguom11,#rmguom12,#rmguom13,#rmguom14,#rmguom15{
width: 50px;
height: 30px;
}
#rmggn{
width: 200px;
height: 30px;
}
#rmggi{
width: 100px;
height: 30px;
}
You need to add type="button" since the default action in some browsers is a submit
<button type="button" ....>C</button>
<button type="button" ....>E</button>
Alternatively add ;return false to your onclick events like this:
onclick="add_Row(); return false"
to not submit the page
Better would be to assign the event handlers in an onload event but still you need to preventDefault the button's click event if it is not type="button"