How to populate modals individually from input in every row? - javascript

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'>&plus;</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}">&plus;</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;">

Related

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
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>

Adding table row for only specific table

I have a table of two for different exercise and my goal is to be able to add new row for each exercise. Below I have a working snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- Icons -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
body {
color: #404E67;
background: #F5F7FA;
font-family: 'Open Sans', sans-serif;
}
.table-wrapper {
width: 40%;
margin: 30px auto;
background: transparent;
padding: 20px;
border-style: solid;
height: 50%;
}
.table-title {
padding-bottom: 10px;
margin: 0 0 10px;
}
.table-title h2 {
margin: 6px 0 0;
font-size: 22px;
}
table.table {
margin-left: em;
}
table.table tr th,
table.table tr td {
border-color: #e9e9e9;
position: relative;
}
table.table th i {
font-size: 13px;
margin: 0 5px;
cursor: pointer;
}
table.table th:last-child {
width: 100px;
}
table.table td a {
cursor: pointer;
display: inline-block;
margin: 0 5px;
min-width: 24px;
}
table.table td a.add {
color: #27C46B;
}
table.table td a.edit {
color: #FFC107;
}
table.table td a.delete {
color: #E34724;
}
table.table td i {
font-size: 19px;
}
table.table td a.add i {
font-size: 24px;
margin-right: -1px;
position: relative;
top: 3px;
}
table.table .form-control {
height: 32px;
line-height: 32px;
box-shadow: none;
border-radius: 2px;
position: absolute;
width: calc(100% - 24px);
padding: 0px;
}
table.table .form-control.error {
border-color: #f50000;
}
table.table td .add {
display: none;
}
table th {
width: auto !important;
color: white;
text-align: center;
vertical-align: middle;
}
td {
color: white;
text-align: center;
vertical-align: middle;
}
.head {
background-color: #4D4F5C;
border-bottom: 3px solid white;
}
#body {
background-color: #4D4F5C;
}
#add_button {
margin-left: 9.5em;
}
h4 {
text-align: center;
}
#name {
text-align: center;
}
#reps {
text-align: center;
}
#weight {
text-align: center;
}
#edit {
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add-new").click(function() {
$(this).attr("disabled", "disabled");
var index = $("table tbody tr:last-child").index();
var row =
'<tr>' +
'<td><input type="text" class="form-control" name="name" id="name"></td>' +
'<td><input type="text" class="form-control" name="weight" id="weight"></td>' +
'<td><input type="text" class="form-control" name="reps" id="reps"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table").append(row);
$("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function() {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function() {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function() {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function() {
$(this).parents("tr").find("td:not(:last-child)").each(function() {
$(this).html('<input type="text" class="form-control w-2" id="edit" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function() {
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
</script>
</head>
<body>
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<h4>AB ROLL OUTS</h4>
</div>
<table class="table table-borderless">
<thead>
<tr class="head">
<th>Set</th>
<th>Weight(Kg)</th>
<th>Reps</th>
<th></th>
</tr>
</thead>
<tbody class="" id="body">
<tr>
<td>1</td>
<td>30</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
<tr>
<td>2</td>
<td>30</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
<button id="add_button" type="button" class="btn btn-dark add-new"><i class="fa fa-plus"></i> Add Set</button>
</div>
<div class="table-wrapper">
<div class="table-title">
<h4>AB ROLL OUTS</h4>
</div>
<table class="table table-borderless">
<thead>
<tr class="head">
<th>Set</th>
<th>Weight(Kg)</th>
<th>Reps</th>
<th></th>
</tr>
</thead>
<tbody class="" id="body">
<tr>
<td>1</td>
<td>20</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
<tr>
<td>2</td>
<td>15</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
<button id="add_button" type="button" class="btn btn-dark add-new"><i class="fa fa-plus"></i> Add Set</button>
</div>
</div>
</body>
</html>
As you can see, if you try to add a new set to one exercise, it will also add a new line for the other exercise, which is not what I wanted. What I want is to be able to add a new set for specific exercise, without a new row being automatically added to another exercise.
How can I achieve this?
You have to uniquely identify each table and button in order to accomplish this. The easiest way is to add an unique id attribute to each table, then add that same value to a name attribute on the respective button.
Meaning, if we call the first table "table1" it needs an id attribute that equals "table1".. then the 'Add Set' button for that table needs to have a name attribute that is also "table1"..(keep in mind I am just using the value "table1" as an example - "table1" could be any value you want, just as long as they match... they have to match due to how I coded the function) For example:
<table id="table1"> ...
<button name="table1">...
This is just one way to do it.. You can do it differently.. the trick is just making sure you can uniquely identify each table and the button on that table..
I have made comments in the code below to make things more legible/understandable..
Demo:
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
//
// ** Get the unique value we are using from the button **
//
let tableName = $(this).attr('name');
//
// ** Use the unique value on that button, to find the table **
//
var index = $(`#${tableName} tbody tr:last-child`).index();
var row =
'<tr>' +
'<td><input type="text" class="form-control" name="name" id="name"></td>' +
'<td><input type="text" class="form-control" name="weight" id="weight"></td>' +
'<td><input type="text" class="form-control" name="reps" id="reps"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
//
// ** Use the unique value to append row to correct table **
//
$(`#${tableName}`).append(row);
$(`#${tableName} tbody tr`).eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("td:not(:last-child)").each(function () {
$(this).html('<input type="text" class="form-control w-2" id="edit" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
body {
color: #404E67;
background: #F5F7FA;
font-family: 'Open Sans', sans-serif;
}
.table-wrapper {
width: 40%;
margin: 30px auto;
background: transparent;
padding: 20px;
border-style: solid;
height: 50%;
}
.table-title {
padding-bottom: 10px;
margin: 0 0 10px;
}
.table-title h2 {
margin: 6px 0 0;
font-size: 22px;
}
table.table {
margin-left: em;
}
table.table tr th,
table.table tr td {
border-color: #e9e9e9;
position: relative;
}
table.table th i {
font-size: 13px;
margin: 0 5px;
cursor: pointer;
}
table.table th:last-child {
width: 100px;
}
table.table td a {
cursor: pointer;
display: inline-block;
margin: 0 5px;
min-width: 24px;
}
table.table td a.add {
color: #27C46B;
}
table.table td a.edit {
color: #FFC107;
}
table.table td a.delete {
color: #E34724;
}
table.table td i {
font-size: 19px;
}
table.table td a.add i {
font-size: 24px;
margin-right: -1px;
position: relative;
top: 3px;
}
table.table .form-control {
height: 32px;
line-height: 32px;
box-shadow: none;
border-radius: 2px;
position: absolute;
width: calc(100% - 24px);
padding: 0px;
}
table.table .form-control.error {
border-color: #f50000;
}
table.table td .add {
display: none;
}
table th {
width: auto !important;
color: white;
text-align: center;
vertical-align: middle;
}
td {
color: white;
text-align: center;
vertical-align: middle;
}
.head {
background-color: #4D4F5C;
border-bottom: 3px solid white;
}
#body {
background-color: #4D4F5C;
}
#add_button {
margin-left: 9.5em;
}
h4 {
text-align: center;
}
#name {
text-align: center;
}
#reps {
text-align: center;
}
#weight {
text-align: center;
}
#edit {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- Icons -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<h4>AB ROLL OUTS</h4>
</div>
<!--
==========================================================================
** Give each table an id **
** this id must match the NAME attribute on the 'Add Set' button
==========================================================================
-->
<table id="table1" class="table table-borderless">
<thead>
<tr class="head">
<th>Set</th>
<th>Weight(Kg)</th>
<th>Reps</th>
<th></th>
</tr>
</thead>
<tbody class="" id="body">
<tr>
<td>1</td>
<td>30</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
<tr>
<td>2</td>
<td>30</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
<!--
=============================================================================
** Give each button a name attribute **
** this name attribute must match the ID attribute on the correct Table **
=============================================================================
-->
<button name="table1" id="add_button" type="button" class="btn btn-dark add-new"><i class="fa fa-plus"></i> Add Set</button>
</div>
<div class="table-wrapper">
<div class="table-title">
<h4>AB ROLL OUTS</h4>
</div>
<!--
==========================================================================
** Give each table an id **
** this id must match the NAME attribute on the 'Add Set' button **
==========================================================================
-->
<table id="table2" class="table table-borderless">
<thead>
<tr class="head">
<th>Set</th>
<th>Weight(Kg)</th>
<th>Reps</th>
<th></th>
</tr>
</thead>
<tbody class="" id="body">
<tr>
<td>1</td>
<td>20</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
<tr>
<td>2</td>
<td>15</td>
<td>12</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
<!--
=============================================================================
** Give each button a name attribute **
** this name attribute must match the ID attribute on the correct Table **
=============================================================================
-->
<button name="table2" id="add_button" type="button" class="btn btn-dark add-new"><i class="fa fa-plus"></i> Add Set</button>
</div>
</div>
</body>
</html>

Cant save content editable to localstorage?

I want to save the content editable data to local storage.
Right now if you try to edit the stock table it changes, then when you refresh the page, it goes back to initial value.
Is there a way to do this automatically, without requiring a button to save it? Just by exiting the text box, it should save automatically.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Inventory</title>
<link href="https://fonts.googleapis.com/css?family=Anton|Titan+One" rel="stylesheet">
<style type="text/css">
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
#hewrap{
text-align: center;
}
#he {
font-family: 'Titan One', cursive;
font-family: 'Anton', sans-serif;
color: white;
background-color: black;
font-size: 32px;
}
.fi {
border-radius:5px;
height: 30px;
}
#btn {
border-radius: 5px;
height: 30px;
background-color: blue;
color:white;
}
#ftr {
background-color: black;
}
</style>
</head>
<body>
<a class="c-link" href='' onclick='javascript:clearLocal();'>Clear storage</a>
<div id="hewrap">
<h1 id="he">Inventory</h1>
</div>
<table id="inventory">
<thead>
<tr>
<th>Description</th>
<th>Part-#</th>
<th>Required</th>
<th>Stock</th>
<th>Price</th>
<th>N/A</th>
</tr>
<tr id="ftr">
<td><input class="fi" type="text" id="one" placeholder="Description"></td>
<td><input class="fi" type="text" id="two" placeholder="Part-#"></td>
<td><input class="fi" type="text" id="three" placeholder="Required"></td>
<td><input class="fi" type="text" id="four" placeholder="Stock"></td>
<td><input class="fi" type="text" id="five" placeholder="Price"></td>
<td><button id="btn" onclick="addRow()">ADD</button></td>
</tr>
</thead>
<tbody id="screen">
</tbody>
</table>
</body>
<script>
//scribble data
//save
$( document ).ready(function(){
$('#screen').html(localStorage.getItem("data"));
});
function addRow(){
var str = '<tr class = "boxType"><td>'+$('#one').val()+'</td>\
<td>'+$('#two').val()+'</td>\
<td>'+$('#three').val()+'</td>\
<td id="scribble" contenteditable="true" onkeyup="storeUserScribble(this.id);">'+$('#four').val()+'</td>\
<td>'+$('#five').val()+'</td>\
</tr>'
$('#screen').append(str);
localStorage.setItem("data", $('#screen').html());
}
</script>
<script type="text/javascript">
getUserScribble();
</script>
</html>

HTML Form resets my Javascript variable [duplicate]

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>

iFrame not loading in Chrome unless window is resized

I have a web page as below which has Invoice numbers on the left side and when a user clicks on it, its details are loaded in iframe(id='invoiceFrame') which works fine in IE but in Chrome iframe is not loaded unless the window is resized
Google Chrome Version 42.0.2311.90 (Official Build) m (32-bit)
<script type="text/javascript">
function getUrlParameter(URL, param){
var paramTokens = URL.slice(URL.indexOf('?') + 1).split('&');
for (var i = 0; i < paramTokens.length; i++) {
var urlParams = paramTokens[i].split('=');
if (urlParams[0].endsWith(param)) {
return urlParams[1];
}
}
}
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
jQuery(document).ready(function () {
jQuery("#mainFrame").hide();
jQuery('#invoiceList tr:not(:first-child)').click(function(e){
jQuery(".message").hide();
e.preventDefault();
var invoiceNumber = jQuery(this).find("td").eq(0).text();
var url = window.location.href;
var lipId = getUrlParameter(url, 'lipId')
var invURL = '/CP/Invoice/InvoiceLineErrors.do?lipId='+lipId+'&invNum='+invoiceNumber;
console.log('invoiceNumber '+invURL);
jQuery("#mainFrame").show();
document.getElementById("mainFrame").src =invURL;
});
});
</script>
<style>
h2.message{text-align: center; color: #FDFDFD; font-size: 1.1em; background: #708fc3; }
#invoiceList{ float: left; width: 15%; overflow-x:auto; }
#invoiceFrame{float: right; width: 83.5%; margin-bottom: 0em !important; }
td error { color: red; font-size: 100%;}
tr.errortrue { color: #c33; font-size: 100%; font-weight: bold;}
table#lines th { background-color : grey; color: white; width:100%}
table {margin-bottom: 2em; border-bottom: 2px solid #ebebeb; empty-cells: show; border-collapse: collapse; }
table#lines td { text-align: center; width:100%}
iframe { float: left; width: 100%; height =300px;
}
</style>
</head>
<body id='foo'>
<div class="ui-widget">
<center><h1> Invoice Error Details For ePacket P00000080235</h1></center>
<div class="panel ui-widget-content" id="invoiceList">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; font-size: 1.1em; "><span>Invoices</span></h2>
<table cellspacing='0' id='header' class="ui-widget">
<tr>
<th>Invoice Number</th>
<th>Invoice Total</th>
</tr>
<tr class = 'errortrue'>
<td>2015.04.08.001</td>
<td>59.97</td>
</tr>
</table>
</div>
<!-- <div class='panel ui-widget-content' id="invoiceDetails">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; "><span>Select the Invoice Number on the left to view the error details</span></h2>-->
<h2 class='message'><span>Select the Invoice Number on the left to view the error details</span></h2>
<div class='panel ui-widget-content' id="invoiceFrame"><iframe src="" id="mainFrame" name="mainFrame" scrolling="no" class='panel ui-widget-content' onload='javascript:resizeIframe(this);'></iframe>
</div>
</div>
</body>
Below is the content of the iframe
<script type="text/javascript">
jQuery('table#lines tr').each(function(){
if (jQuery(this).html() == '') {
jQuery(this).hide();
}
});
</script>
<style>
#invoice {padding: 0;}
#invoiceErrors {overflow-x: auto; overflow-y: auto;}
tbody td{ border-top: 2px solid #efefef; border-bottom: 0px !important ;}
td.error { text-align: left; color: #c33; font-size: 100%; background-image: none !important; padding-left : 0; border-bottom: 2px solid #0891F4; white-space: nowrap;}
tr.errortrue { color: #c33; font-size: 100%; font-weight: bold; white-space: nowrap;}
table {empty-cells: show; border-collapse: collapse; }
table#lines td { text-align: left;}
</style>
</head>
<body id='invoice'>
<div id="invoiceErrors">
<div class='panel ui-widget-content' id="invoiceHeaders">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; font-family: Tahoma,Arial,sans-serif; font-size: 1.2em;"><span>Header Details</span></h2>
<table class="ui-widget" id="headers">
<tr>
<th>Invoice Number</th>
<th>Matter Number</th>
<th>Invoice Total</th>
<th>Invoice Tax Total</th>
<th>Invoice Net Total</th>
</tr>
<tr class='errortrue'>
<td>2015.04.08.001</td>
<td>MAT-2</td>
<td>59.97</td>
<td>59.97</td>
<td>59.97</td>
</tr>
<tr ><td class = 'error' style="padding-bottom: 4%;">
Line : 1 Invoice tax total does not foot Reported = (0.0) Calculated = (1.0)<br/>
Line : 1 Invoice Taxable Amount does not foot Reported = (59.97) Calculated = (58.97)<br/>
</td></tr>
</table>
</div>
<div class='panel ui-widget-content' id="invoiceLines">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; font-family: Tahoma,Arial,sans-serif; font-size: 1.2em;"><span>Invoice Line Items</span></h2>
<table class="ui-widget" id="lines">
<tr>
<th>Line Item Number</th>
<th>Line Item Date</th>
<th>Unit Cost</th>
<th>Number of Units</th>
<th>Line Item Total</th>
</tr>
<tr class='errortrue'>
<td>1</td>
<td>20150402</td>
<td>19.99</td>
<td>3</td>
<td>59.97</td>
</tr>
<tr>
<td colspan="9" class='error' style="padding-bottom: 6%;">
Line : 1 MATH ERROR: ((19.99*3.0) - (0.0)) * (1.0) != 1.0 variance = 58.97<br/>
Line : 1 MATH ERROR: (19.99*3.0) - (0.0) + (1.0) != 59.97 variance = 1.0<br/>
</td>
</tr>
</table>
</div>
</div>
</body>
Can someone please help me with the iframe issue?
Try adding position to iframe
iframe { float: left; width: 100%; height :300px; position:relative}
I used this workaround to make it work:
var iframe = $('<iframe>', {
src: url,
frameborder: 0,
load: function () {
// fixes Chrome not painting iframe until window resizes
// https://bugs.chromium.org/p/chromium/issues/detail?id=481922
iframe.contents().find('body').hide(0).show(0);
// end repaint fix
}
});
adding this to the css customizer fixed our issue:
iframe {width:100%!important;}

Categories

Resources