newbie here.. I was looking for some kind of function that can total the amount of one input type in table which is the Amount input.
I've tried parseInt function to the amount and its cell but it doesn't work.
I think its getting only the .innerHTML but not what it contains which should be the number.
var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;
//click button event
entryButton.addEventListener('click', tableDisplay);
//input value and displaying information
function tableDisplay(e) {
e.preventDefault()
var name = document.getElementById('inputName').value;
var amount = document.getElementById('inputAmount').value;
var date = document.getElementById('inputDate').value;
var remarks = document.getElementById('inputRemarks').value;
document.getElementById('inputName').value = '';
document.getElementById('inputAmount').value = '';
document.getElementById('inputDate').value = '';
document.getElementById('inputRemarks').value = '';
if (!name || !amount || !date || !remarks) {
alert("Please fill all the blanks")
return;
}
name.value = " ";
amount.value = " ";
date.value = " ";
remarks.value = " ";
var table = document.getElementById('displayTable');
var newRow = table.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = name
cell2.innerHTML = date
cell3.innerHTML = amount
cell4.innerHTML = remarks
selectedRow()
row++;
}
//adding total amount function??
<!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.0" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
<link
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css"
rel="stylesheet"
/>
<link
href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1 class="d-flex justify-content-center mb-5 mt-5">Expense Tracker</h1>
<form class="form d-flex justify-content-center mb-5">
<span class="fw-bolder m-1"
>Name: <input class="m-1" id="inputName" type="text"
/></span>
<span class="fw-bolder m-1"
>Date: <input class="m-1" id="inputDate" type="date"
/></span>
<span class="fw-bolder m-1"
>Amount: <input type="number" class="totalAmount m-1" id="inputAmount"
/></span>
<span class="fw-bolder m-1"
>Remarks <input class="m-1" id="inputRemarks" type="text"
/></span>
<button class="m-1" id="inputButton">
<i class="icon-level-down fs-4"></i>
</button>
<!-- How to delete specific row -->
<button class="m-1" type="button" id="deleteSelection">
<i class="icon-remove-sign fs-4"></i>
</button>
</form>
<table class="table m-5" id="displayTable">
<thead>
<tr id="numero">
<th scope="col">
<i class="icon-file-text fw-bolder fs-3"></i> Description
</th>
<th scope="col"><i class="icon-calendar fw-bolder fs-3"></i> Date</th>
<th scope="col"><i class="icon-usd fw-bolder fs-3"></i> Amount</th>
<th scope="col"><i class="icon-pencil fs-3"></i> Remarks</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- //passing total amount?? -->
<span class="d-flex justify-content-center"
>Total: <input type="number" id="total" value="0" disabled
/></span>
<script src="script.js"></script>
</body>
</html>
I created a function called total(), which calculates the total of the column 'Amount' and prints it inside the input #total.
var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;
//click button event
entryButton.addEventListener('click', tableDisplay);
//input value and displaying information
function tableDisplay(e) {
e.preventDefault()
var name = document.getElementById('inputName').value;
var amount = document.getElementById('inputAmount').value;
var date = document.getElementById('inputDate').value;
var remarks = document.getElementById('inputRemarks').value;
document.getElementById('inputName').value = '';
document.getElementById('inputAmount').value = '';
document.getElementById('inputDate').value = '';
document.getElementById('inputRemarks').value = '';
if (!name || !amount || !date || !remarks) {
alert("Please fill all the blanks")
return;
}
name.value = " ";
amount.value = " ";
date.value = " ";
remarks.value = " ";
var table = document.getElementById('displayTable');
var newRow = table.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = name
cell2.innerHTML = date
cell3.innerHTML = amount
cell4.innerHTML = remarks
total()
row++;
}
function total(){
var table = document.getElementById('displayTable');
let total = 0
for(let i = 1; i<table.rows.length; i++){
total+=Number(table.rows[i].cells[2].innerText)
}
const totalInput = document.getElementById('total')
totalInput.value=total
}
Related
Im trying to do a expense tracker with vanilla javascript that user can can add/remove their expense item and the Total of expense will be calculated accordingly.
I am using constructor to create object so later I can save in localStorage later and retrieve later (hv not done this part yet)
Here is the problem. There is no problem in adding atm but when it comes to removing item (if not remove in sequence), the calculation is messed up. E.g. Item 1, Item 2, Item 3. If I remove with order Item 3 --> Item2 --> Item No problem with total value of subtraction. But if start the removal from Item 1 or Item 2, the calculation will be messed up
Im not sure is it because there is no index/id in each item so calculation is not working. Appreciate for any help thank you!
<!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.0">
<link rel="stylesheet" href="ExpenseTracker.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<label name="expense">Expense: </label>
<input id="inputField" name="expense" type="text">
<label name="date">Date: </label>
<input id="start" type="text" name="date">
<label name="amount">Amount: </label>
<input id="money" name="amount" type="number" min="0" step="0.1">
<button id="add" >Add</button>
<table>
<thead>
<tr style="border: 1px solid black;">
<th>Description</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="listContainer" style="border: 1px solid black;">
</tbody>
<tr>
<td id="total">total</td>
</tr>
</table>
<button onclick="clearHistory()">clear localStorage</button>
</div>
<script>
class ExpenseObject{
constructor(e, d, a){
this.expenseDescription = e;
this.dateObject = d;
this.amount = a;
}
}
function clearHistory(){
localStorage.clear();
}
const createDate = flatpickr("#start",{
dateFormat:"d-m-Y ",
});
let addButton = document.getElementById("add");
let listContainer=document.getElementById("listContainer");
let inputField= document.getElementById("inputField");
let dateInput = document.getElementById("start");
let amountField = document.getElementById("money");
let total = document.getElementById("total");
addButton.addEventListener('click', function(){
if(!inputField.value || !dateInput.value || !amountField.value){
alert("please do not leave blank in any field");
return;
}
var newRow = document.createElement('tr');
var expense = document.createElement('td');
var expenseDate = document.createElement('td');
var expenseAmount = document.createElement('td');
var deleteButton = document.createElement('button');
deleteButton.innerHTML="X";
let expenseStuff = new ExpenseObject (inputField.value,dateInput.value,amountField.value )
expense.innerHTML = expenseStuff.expenseDescription;
expenseDate.innerHTML = expenseStuff.dateObject;
expenseAmount.innerText = expenseStuff.amount;
listContainer.appendChild(newRow);
newRow.appendChild(expense);
newRow.appendChild(expenseDate);
newRow.appendChild(expenseAmount);
newRow.appendChild(deleteButton);
inputField.value = "";
amountField.value="";
var totalAmount = parseFloat(total.innerText) || 0;
totalAmount += parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
deleteButton.addEventListener('click', function(){
newRow.removeChild(expense);
newRow.removeChild(expenseDate);
newRow.removeChild(expenseAmount);
newRow.removeChild(deleteButton);
totalAmount -= parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
})
})
</script>
</body>
</html>
The primary issue you were experiencing is that you declared totalAmount at the local scope, so each deleteButton event listner still references the old totalAmount value from when the listener was declared. If you declare that value in a higher-level scope, alongside total, everything works as expected.
Here it is in action:
<!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.0">
<link rel="stylesheet" href="ExpenseTracker.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<label name="expense">Expense: </label>
<input id="inputField" name="expense" type="text">
<label name="date">Date: </label>
<input id="start" type="text" name="date">
<label name="amount">Amount: </label>
<input id="money" name="amount" type="number" min="0" step="0.1">
<button id="add" >Add</button>
<table>
<thead>
<tr style="border: 1px solid black;">
<th>Description</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="listContainer" style="border: 1px solid black;">
</tbody>
<tr>
<td id="total">total</td>
</tr>
</table>
<button onclick="clearHistory()">clear localStorage</button>
</div>
<script>
class ExpenseObject{
constructor(e, d, a){
this.expenseDescription = e;
this.dateObject = d;
this.amount = a;
}
}
function clearHistory(){
localStorage.clear();
}
const createDate = flatpickr("#start",{
dateFormat:"d-m-Y ",
});
let addButton = document.getElementById("add");
let listContainer = document.getElementById("listContainer");
let inputField = document.getElementById("inputField");
let dateInput = document.getElementById("start");
let amountField = document.getElementById("money");
let total = document.getElementById("total");
let totalAmount = parseFloat(total.innerText) || 0;
addButton.addEventListener('click', function(){
if(!inputField.value || !dateInput.value || !amountField.value){
alert("please do not leave blank in any field");
return;
}
const newRow = document.createElement('tr');
const expense = document.createElement('td');
const expenseDate = document.createElement('td');
const expenseAmount = document.createElement('td');
const deleteButton = document.createElement('button');
deleteButton.innerHTML="X";
let expenseStuff = new ExpenseObject (inputField.value,dateInput.value,amountField.value )
expense.innerHTML = expenseStuff.expenseDescription;
expenseDate.innerHTML = expenseStuff.dateObject;
expenseAmount.innerText = expenseStuff.amount;
listContainer.appendChild(newRow);
newRow.appendChild(expense);
newRow.appendChild(expenseDate);
newRow.appendChild(expenseAmount);
newRow.appendChild(deleteButton);
inputField.value = "";
amountField.value = "";
totalAmount += parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
deleteButton.addEventListener('click', function() {
newRow.removeChild(expense);
newRow.removeChild(expenseDate);
newRow.removeChild(expenseAmount);
newRow.removeChild(deleteButton);
totalAmount -= parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
})
})
</script>
</body>
</html>
I am building a sample project named Tennis Club Management based on HTML,CSS,Javascript.In this i have html pages like profile.html, manageFees.html,index.js etc. In manageFees.html, when the page gets loaded, a dynamic table gets displayed which shows data from online API in tabular format and there is also a search box for searching the records.
Problem :- When i search a particular data(record) in search box. the search result gets displayed in the table , but the table heading gets disappeared and table CSS properties get distorted.
Below are the code files and Screenshots
index.js
/* --------------------MANAGE FEES PAGE------------------- */
/*----------TESTING CODE FOR SHOW FEES-----------*/
function showfees() {
console.log("Show Fees button clicked...");
document.querySelector(".showfees").style.display = "none";
document.querySelector("#feesregistration").style.display = "none";
if (istableCreated) {
document.querySelector("#table-responsive").style.display = "none";
}
document.querySelector(".searchbox").style.display = "block";
if (istableCreated == false) {
istableCreated = true;
var myTable = document.createElement("table");
myTable.className = "table-responsive";
myTable.id = "table-responsive";
myTable.style.marginLeft = "15%";
myTable.style.paddingLeft = "8%";
myTable.style.paddingRight = "11%";
document.body.appendChild(myTable);
var maintr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(maintr);
var thmatchID = document.createElement("th");
thmatchID.innerHTML = "Match ID";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thmatchID);
var thmatchplayerName = document.createElement("th");
thmatchplayerName.innerHTML = "Player Name";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thmatchplayerName);
var thmatchDate = document.createElement("th");
thmatchDate.innerHTML = "Fees Date";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thmatchDate);
var thFeesAmount = document.createElement("th");
thFeesAmount.innerHTML = "Amount";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thFeesAmount);
var thMembershipType = document.createElement("th");
thMembershipType.innerHTML = "Membership Type";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thMembershipType);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
var JSONarr = JSON.parse(this.responseText);
console.log(JSONarr);
// ----------SUPER TESTING CODE-----------
for (var i = 0; i < JSONarr.length; i++) {
console.log(JSONarr[i].id, JSONarr[i].name, JSONarr[i].address.city, JSONarr[i].address.zipcode);
var myTr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(myTr);
var tdID = document.createElement("td");
tdID.innerHTML = `${JSONarr[i].id}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdID);
var tdplayerName = document.createElement("td");
tdplayerName.innerHTML = `${JSONarr[i].name}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdplayerName);
var tdAddress = document.createElement("td");
tdAddress.innerHTML = `04/04/2020`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdAddress);
var tdFeesAmount = document.createElement("td");
tdFeesAmount.innerHTML = `10000`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdFeesAmount);
var tdMembershipType = document.createElement("td");
tdMembershipType.innerHTML = `Annually`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdMembershipType);
}
}
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users", true);
xhttp.send();
}
else {
document.querySelector("#table-responsive").style.display = "block";
}
if (statictableboolean == true) {
document.querySelector(".staticTable").style.display = "none";
}
// document.querySelector(".staticTable").style.display = "none";
}
//-------------SEARCHING IMPLEMENTATION IN SEARCH BOX----------------
function mySearch() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("searchbox");
filter = input.value.toUpperCase();
table = document.getElementById("table-responsive");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
}
else {
tr[i].style.display = "none";
}
}
}
manageFees.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Fees</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 onload="showfees()">
<!-- ADDING BUTTONS LIKE SHOW MATCHES, ADD MATCHES USING CSS BOOTSTRAP -->
<!-- <button type="button" class="btn btn-secondary showfees" onclick="showfees()">Show Fees</button> -->
<button type="button" class="btn btn-secondary addfees" onclick="addfees()">Add Fees</button>
<button type="button" class="btn btn-danger showfees" onclick="showfees()">Back</button>
<!-- ADDING SEARCH BAR -->
<input type="text" class="searchbox" id="searchbox" onkeyup="mySearch()" placeholder="Search by ID...">
<!-- CREATING REGISTRATION PAGE FOR ADDING FEES -->
<table class="feesregistration" id="feesregistration">
<!-- <tr>
<td>
<label>ID :</label>
</td>
<td>
<input type="text" class="feesid" id="feesid">
</td>
</tr> -->
<tr>
<td>
<label>Name :</label>
</td>
<td>
<input type="text" class="playerNameFees" id="playerNameFees" maxlength="40">
</td>
<td>
<label class="playerNameFeeserror"></label>
</td>
</tr>
<tr>
<td>
<label>Fees For :</label>
</td>
<td>
<select class="feesFor" id="feesFor">
<option value="select">---Select---</option>
<option value="court">Court</option>
<option value="tournament">Tournament</option>
<option value="both">Both</option>
</select>
</td>
<td>
<label class="feesForerror"></label>
</td>
</tr>
<tr>
<td>
<label>Fee Type :</label>
</td>
<td>
<select class="feesType" id="feesType">
<option value="select">---Select---</option>
<option value="monthly">Monthly</option>
<option value="halfyearly">Half Yearly</option>
<option value="annually">Annually</option>
</select>
</td>
<td>
<label class="feesTypeerror"></label>
</td>
</tr>
<tr>
<td>
<label>Date :</label>
</td>
<td>
<input type="date" class="feesdate">
</td>
<td>
<label class="feesdateerror"></label>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-success savefees" onclick="saveFees()">SAVE</button>
</td>
<td>
<button type="button" class="btn btn-info clearfees" onclick="clearfees()">CLEAR</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
Any solution please ?
I have a table single input field with calendar when i click on input drop down calendar is coming to select the date.
By using javascript i am inserting a new row in the table . Row is inserting in the table but date calendar not coming in new inserted row date field as in above line .
I am using the following code
function addRow() {
var table = document.getElementById("mintable");
var rowCount = parseInt(document.getElementById("minRows").value);
var rowInsert = parseInt(document.getElementById("sizemin").value);
var row = table.insertRow(rowInsert + 1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.id = "minenddate" + (rowCount);
element1.className = "form-control";
cell1.appendChild(element1);
rowCount = parseInt(rowCount) + 1;
document.getElementById("minRows").value = rowCount;
document.getElementById("sizemin").value =
parseInt(document.getElementById("sizemin").value) + 1;
}
$(function() {
count = document.getElementById("minsize").value;
i = 0;
dateId = "datepicker2";
for (i = 0; i <= (count + 1); i++) {
dateId = "#datepicker2" + i;
$(dateId).datepicker();
}
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<input type="hidden" id="minsize" value="1">
<div class="">
<table id="mintable" class="table table-bordered table-striped stripe hover row-border">
<thead class="div-head">
<tr>
<th><b>Date</b></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id='datepicker20' value="2018-08-09" class="form-control"></td>
</tr>
</tbody>
</table>
<input type="hidden" name="minRows" id="minRows" value='1'>
<input type="hidden" id="sizemin" name="sizemin" value='1' />
</div>
<input type="submit" data-toggle="tooltip" title="Insert new horizon
" data-placement="top" class="btn btn-primary" id="button" value="Add Row" onClick="addRow()" />
You have to re-initialize the datepicker on dynamically added
elements.
Here's how to add it.
$('#'+element1.id).datepicker();
function addRow() {
var table = document.getElementById("mintable");
var rowCount = parseInt(document.getElementById("minRows").value);
var rowInsert = parseInt(document.getElementById("sizemin").value);
var row = table.insertRow(rowInsert + 1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.id = "minenddate" + (rowCount);
element1.className = "form-control";
cell1.appendChild(element1);
$('#' + element1.id).datepicker(); //add this line to initialize
rowCount = parseInt(rowCount) + 1;
document.getElementById("minRows").value = rowCount;
document.getElementById("sizemin").value =
parseInt(document.getElementById("sizemin").value) + 1;
}
$(function() {
count = document.getElementById("minsize").value;
i = 0;
dateId = "datepicker2";
for (i = 0; i <= (count + 1); i++) {
dateId = "#datepicker2" + i;
$(dateId).datepicker();
}
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="resources/js/jquery.dataTables.min.js"></script>
<script src="resources/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<input type="hidden" id="minsize" value="1">
<div class="">
<table id="mintable" class="table table-bordered table-striped stripe hover row-border">
<thead class="div-head">
<tr>
<th><b>Date</b></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id='datepicker20' value="2018-08-09" class="form-control" /></td>
</tr>
</tbody>
</table>
<input type="hidden" name="minRows" id="minRows" value='1'>
<input type="hidden" id="sizemin" name="sizemin" value='1' />
</div>
<input type="submit" data-toggle="tooltip" title="Insert new horizon
" data-placement="top" class="btn btn-primary" id="button" value="Add Row" onClick="addRow()" />
I have a HTML form. The save and delete button are working fine. But I want to write JavaScript (not jQuery or AngularJS) code of edit and update button. When I click the edit the data of particular row should be displayed in the textboxes and when I press update button the updated data of that particular row should get submitted in the HTML table.
function addRow() {
var id= document.getElementById("id");
var name= document.getElementById("name");
var gender= document.getElementById("gender");
var address= document.getElementById("address");
var email = document.getElementById("email");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= id.value;
row.insertCell(1).innerHTML= name.value;
row.insertCell(2).innerHTML= gender.value;
row.insertCell(3).innerHTML= address.value;
row.insertCell(4).innerHTML= email.value;
row.insertCell(5).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(6).innerHTML= '<input type="button" value = "Edit" onClick="Javacsript:updateRow(this)">';
id.value="";
name.value="";
gender.value="";
address.value="";
email.value="";
}
function updateRow(obj){
}
function reset(){
var id= document.getElementById("id");
var name= document.getElementById("name");
var gender= document.getElementById("gender");
var address= document.getElementById("address");
var email = document.getElementById("email");
var table = document.getElementById("myTableData");
id.value="";
name.value="";
gender.value="";
address.value="";
email.value="";
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
}
Add Function will look like this..
function addRow() {
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var id = document.getElementById("id");
var name = document.getElementById("name");
var gender = document.getElementById("gender");
var address = document.getElementById("address");
var email = document.getElementById("email");
var cell1 = row.insertCell(0);
cell1.innerHTML=id.value;
var cell2 = row.insertCell(1);
cell2.innerHTML = name.value;
var cell3 = row.insertCell(2);
cell3.innerHTML = gender.value;
var cell4 = row.insertCell(3);
cell4.innerHTML = address.value;
var cell5 = row.insertCell(4);
cell5.innerHTML = email.value;
var cell6 = row.insertCell(5);
var strHtml5 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"UpdateRow(" + rowCount + ")\" VALUE=\"Update Row\">|<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow(" + rowCount + ")\" VALUE=\"Delete Row\">";
cell6.innerHTML = strHtml5;
}
</script>
I copied your code and executed in my machine and found minor errors as well as big mistake you did by not using form tag and created the form.
After reverse engineering I appended your code and made it fully functional as well as simple to understand.
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<!-- ### <script type="text/javascript" src="D:\LatestNewProject-JavaScript\script.js"></script> -->
</head>
<body>
<div id="myform">
<b>Employee Information</b>
<form method="post" action=""> <!-- ###Form tag is not used -->
<table>
<tr>
<td>ID:</td> <!-- ###change id to empId as id="id" will cause ambiguity -->
<td><input type="text" id="empId"></td> <!-- ###use text field instead of number to make input of 3 digit no. easy -->
</tr>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Gender:</td> <!-- ### imstead of select option you must use radio button -->
<td> <input type="radio" id="gender" value="male" /> Male <br>
<input type="radio" id="gender" value="Female" /> FeMale
</td>
</tr>
<tr>
<td>Address:</td>
<td><input type="textarea" id="address"></td> <!-- ###insted of text field you should give textarea field-->
</tr>
<tr>
<td>Email:</td> <!-- ###email is new element in HTML5 so, id="email" can cause issue, so email=Email -->
<td><input type="email" id="mail" name="Email"></td>
</tr>
<!-- No need to use this [<table>] --> <!-- ### onclick should be onClick [best practice]-->
<tr>
<td><input type="button" id="add" value="Add" onclick="javascript:addRow()"></td>
<td><input type="reset" value="Reset" /> </td>
<td><input type="button" id="update" value="Update" onClick=""></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Gender</b></td>
<td><b>Address</b></td>
<td><b>Email</b></td>
<td><b>Action</b></td>
</tr>
</table>
</div>
<!-- ============ JavaScript ========== -->
<script>
function addRow() {
var id= document.getElementById("empId");
var name= document.getElementById("name");
var gender= document.getElementById("gender");
var address= document.getElementById("address");
var email = document.getElementById("mail");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= empId.value;
row.insertCell(1).innerHTML= name.value;
row.insertCell(2).innerHTML= gender.value;
row.insertCell(3).innerHTML= address.value;
row.insertCell(4).innerHTML= mail.value;
row.insertCell(5).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(6).innerHTML= '<input type="button" value = "Edit" onClick="Javacsript:updateRow(this)">';
empId.value="";
name.value="";
gender.value="";
address.value="";
mail.value="";
}
function updateRow(obj){
}
function reset(){
var id= document.getElementById("empId");
var name= document.getElementById("name");
var gender= document.getElementById("gender");
var address= document.getElementById("address");
var email = document.getElementById("mail");
var table = document.getElementById("myTableData");
empId.value="";
name.value="";
gender.value="";
address.value="";
mail.value="";
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
</script>
</body>
</html>
my javascript function is below where I am creating the 2 textboxes dynamically each time when the addRow() function is called on button click.Also,I am setting name attribute for each textbox dynamically.but I am not able to access these textbox values from servlet and getting null value as output.
<html>
<head>
<script>
var count=1;
function addRow()
{
var table = document.getElementById('table');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "item "+ count;
// document.write(element1.name);
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "amount" + count;
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = ' <input type="button" value="Edit" onclick="editRow(this)"/><input type="button" value="Delete" onclick="deleteRow(this)"/>';
cell3.setAttribute("style", "display:none;");
var cell4 = row.insertCell(3);
cell4.innerHTML = '<input type="button" value="Save" onClick="saveRow(this)">';
document.listform.hfield.value=rowCount;
count++;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="css/style.css" type="text/css">
<title>Create your list</title>
</head>
<body>
<form name="listform" method="post" action="Billingservlet">
<div class="wrap">
<center>
<div id="display">
<table id='table' border="0">
<tr id='id'>
<th>
Item Name
</th>
<th>
No. of units
</th>
</tr>
</table>
<input type="button" value="Add another item" onclick="addRow()">
<input type="submit" value="Submit List">
<input type="hidden" name="hfield">
</div>
</center>
</div>
</form>
</body>
</html>