how to print json object in my table? - javascript

I am trying to print my object that holds my inputName field and my inputDate field. I am successfully storing both variables onto my localStorage but I am unable to print it in my table. I am proving a picture to a better understanding. I tried to use console.log but It doesn't print anything in the console. I guess I do not know how to use console log.
What I am trying to do is the following : once an user inputs a name and date, I want to be able to display those values to my table.
function SortByKey(array,key){
return array.sort(function(a,b){
var x = a[key];
var y = b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
/* This function will save my input onto Local Storage*/
function getInput(){
var nameInput = document.getElementById('inputName').value;
localStorage.setItem('Name', nameInput);
var dateInput = document.getElementById( 'inputDate').value;
localStorage.setItem('Date', dateInput);
}
function SubmitInput() {
var JsObject =[];
var nameInput = document.getElementById('inputName').value;
var dateInput = document.getElementById('inputDate').value;
if (localStorage.getItem('datastorage')!=undefined) {
var JsObject = JSON.parse(localStorage.datastorage);
}
JsObject.push({'inputName':nameInput, 'inputDate':dateInput});
localStorage.setItem('datastorage',JSON.stringify(JsObject));
//console.log(JsObject);
print();
}
function print (){
var JsObject = JSON.parse(localStorage.getItem('datastorage'));
var clean = " ";
document.getELementByID('myTable').inner.HTML=clean;
for (var i = 0; I < JsObject.length; i++) {
document.getElementById('myTable').innerHTML += "<tr>" + "<td>" + JsObject[i].nameInput + "</td>" + "<td>" + JsObject[i].dateInput + "</td>" + "</tr>";
//console.log(JsObject);
}
}
<style>
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;
}
</style>
</head>
<body>
<table id="myTable" >
<tr>
<th>Name</th>
<th>Date</th>
<th>Endorsement</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<form class="form-horizontal">
<fieldset>
<legend>Endorse me</legend>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input onCLick ="getInput()" type="text" class="form-control" id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date</label>
<div class="col-lg-10">
<input onCLick="getInput()" type="text" class="form-control" id="inputDate" placeholder="Date">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button onClick="SubmitInput()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</fieldset>
</form>
</head>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</body>
</html>

Try This:
function SortByKey(array,key){
return array.sort(function(a,b){
var x = a[key];
var y = b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
/* This function will save my input onto Local Storage*/
function getInput(){
var nameInput = document.getElementById('inputName').value;
localStorage.setItem('Name', nameInput);
var dateInput = document.getElementById( 'inputDate').value;
localStorage.setItem('Date', dateInput);
}
function SubmitInput() {
var JsObject =[];
var nameInput = document.getElementById('inputName').value;
var dateInput = document.getElementById('inputDate').value;
if (localStorage.getItem('datastorage')!=undefined) {
var JsObject = JSON.parse(localStorage.datastorage);
}
JsObject.push({'inputName':nameInput, 'inputDate':dateInput});
localStorage.setItem('datastorage',JSON.stringify(JsObject));
//console.log(JsObject);
print();
}
function print (){
var JsObject = JSON.parse(localStorage.getItem('datastorage'));
var clean = " ";
document.getELementByID('myTable').inner.HTML=clean;
//for (var i = 0; I < JsObject.length; i++) {
/*
document.getElementById('myTable').innerHTML += "<tr>" + "<td>" + JsObject[i].nameInput + "</td>" + "<td>" + JsObject[i].dateInput + "</td>" + "</tr>"; */
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + JsObject[i].nameInput + "</td>");
tr.append("<td>" + JsObject[i].dateInput + "</td>");
tr.append("<td>" + next_variable + "</td>");
$('myTable').append(tr);
}
//console.log(JsObject);
}
<html>
<style>
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;
}
</style>
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> -->
</head>
<body>
<table id="myTable" >
</table>
<form class="form-horizontal">
<fieldset>
<legend>Endorse me</legend>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input onCLick ="getInput()" type="text" class="form-control" id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date</label>
<div class="col-lg-10">
<input onCLick="getInput()" type="text" class="form-control" id="inputDate" placeholder="Date">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button onClick="SubmitInput()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</fieldset>
</form>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</html>

Related

HTML/JS output table not showing horizontal borders

I can't figure out why my horizontal borders are not showing up with my output section. See code and screenshot below:
I would like to have horizontal borders and if possible keep the date fields from
wrapping into the next row below itself.
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
<td align="center"><input type="button" value="Submit" name="submit" id="submit" onClick="display()" /></button></td>
</tr>
</table>
<table width="400px" align="center" colspan="40" table border="5">
<tr style="background-color:#8FBC8F;">
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
<tr>
<td align="center"><div id="displayarea"></div></td>
<td align="center"><div id="displayarea1"></div></td>
<td align="center"><div id="displayarea2"></div></td>
<td align="center"><div id="displayarea3"></div></td>
<td align="center"><div id="displayarea4"></div></td>
</tr>
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
function getValue() {
var Items = "";
var td1 = document.getElementById("displayarea").innerHTML.split("<br>");
var td2 = document.getElementById("displayarea1").innerHTML.split("<br>");
var td3 = document.getElementById("displayarea2").innerHTML.split("<br>");
var td4 = document.getElementById("displayarea3").innerHTML.split("<br>");
var td5 = document.getElementById("displayarea4").innerHTML.split("<br>");
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
document.getElementById("displayarea").innerHTML += document.getElementById("fname").value + "<br />";
document.getElementById("fname").value = "";
document.getElementById("displayarea1").innerHTML += document.getElementById("lname").value + "<br />";
document.getElementById("lname").value = "";
document.getElementById("displayarea2").innerHTML += document.getElementById("sname").value + "<br />";
document.getElementById("sname").value = "";
document.getElementById("displayarea3").innerHTML += document.getElementById("pname").value + "<br />";
document.getElementById("pname").value = "";
document.getElementById("displayarea4").innerHTML += document.getElementById("jname").value + "<br />";
document.getElementById("jname").value = "";
}
I highly suggest you start separating your data from your presentation of that data.
So, split your display function into two: createRow and renderRows. Likewise, getValues can just be getRows.
Note that this required a different way of doing things in your code, so I also refactored your HTML and CSS to bring it more in line with modern methods.
function getRows(data) {
return data.map(datum => Object.values(datum).join(',')).join('\n');
}
function createRow(data) {
const datum = {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value,
sname: new Date(document.getElementById("sname").valueAsNumber).toLocaleString(),
pname: new Date(document.getElementById("pname").valueAsNumber).toLocaleString(),
jname: document.getElementById("jname").value
};
data.push(datum);
document.getElementById("dataForm").reset();
renderRows(data);
}
function renderRows(data) {
const body = document.getElementById("renderedData");
body.innerHTML = "";
for (let datum of data) {
let tr = document.createElement('tr');
let tdFName = document.createElement('td');
tdFName.appendChild(document.createTextNode(datum.fname));
tr.appendChild(tdFName);
let tdLName = document.createElement('td');
tdLName.appendChild(document.createTextNode(datum.lname));
tr.appendChild(tdLName);
let tdSName = document.createElement('td');
tdSName.appendChild(document.createTextNode(datum.sname));
tr.appendChild(tdSName);
let tdPName = document.createElement('td');
tdPName.appendChild(document.createTextNode(datum.pname));
tr.appendChild(tdPName);
let tdJName = document.createElement('td');
tdJName.appendChild(document.createTextNode(datum.jname));
tr.appendChild(tdJName);
body.appendChild(tr);
}
}
window.addEventListener('load', () => {
const data = [];
document.getElementById('add').addEventListener('click', function(e) {
createRow(data);
});
document.getElementById('getData').addEventListener('click', function(e) {
console.log(getRows(data));
});
});
form {
width: max-content;
margin: 0 auto 1rem;
}
.control-group {
display: flex;
justify-content: space-between;
}
fieldset {
display: flex;
flex-flow: column nowrap;
}
fieldset button {
align-self: flex-end;
}
<form id="dataForm">
<fieldset>
<legend>Enter Data</legend>
<div class="control-group">
<label for="fname">Name:</label>
<input id="fname" type="text">
</div>
<div class="control-group">
<label for="lname">Company:</label>
<input id="lname" type="text">
</div>
<div class="control-group">
<label for="sname">Time In:</label>
<input id="sname" type="datetime-local">
</div>
<div class="control-group">
<label for="pname">Time Out:</label>
<input id="pname" type="datetime-local">
</div>
<div class="control-group">
<label for="jname">Description of Work:</label>
<textarea id="jname"></textarea>
</div>
<button type="button" id="add">Add</button>
</fieldset>
</form>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody id="renderedData">
</tbody>
</table>
<button type="button" id="getData">Get Data</button>
To get borders for all cells, add this at the top of your html code (inside the head):
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid #555;
}
</style>
Adjust the border thickness, style and color as you like (in the border setting of td)
Here's an easy way to add a row with each addition using the element - available in all good browsers (not so fast Internet Explorer, I wasn't talking to you)
I've also changed how to read the values
note, using class instead of id in the cells in the rows - to make it easy to get them all with minimal change to your code
Although, personally I'd get the row data data differently (shown in alternativeGetValues)
function getValue() {
var Items = "";
var td1 = [...document.querySelectorAll(".displayarea")].map(e => e.innerHTML);
var td2 = [...document.querySelectorAll(".displayarea1")].map(e => e.innerHTML);
var td3 = [...document.querySelectorAll(".displayarea2")].map(e => e.innerHTML);
var td4 = [...document.querySelectorAll(".displayarea3")].map(e => e.innerHTML);
var td5 = [...document.querySelectorAll(".displayarea4")].map(e => e.innerHTML);
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ,";
if (td5[i])
Items += td5[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
const template = document.getElementById("row");
const clone = template.content.cloneNode(true);
const additem = (dest, src) => {
const s = document.querySelector(src);
clone.querySelector(dest).innerHTML = s.value;
s.value = "";
};
additem(".displayarea", "#fname");
additem(".displayarea1", "#lname");
additem(".displayarea2", "#sname");
additem(".displayarea3", "#pname");
additem(".displayarea4", "#jname");
template.insertAdjacentElement('beforebegin', clone.firstElementChild);
}
// IMHO this is better
function alternateGetValue() {
const Items = [...document.querySelectorAll('.data')]
.map(row => [...row.querySelectorAll('td>div')]
.map(d => d.textContent).join(',')
).join('\n');
console.log(Items);
return Items;
}
.wide {
min-width:12em;
}
F: <input id="fname"> <br>
L: <input id="lname"> <br>
S: <input id="sname"> <br>
P: <input id="pname"> <br>
J: <input id="jname"> <br>
<input type="button" value="add" onclick="display()"/>
<input type="button" value="show" onclick="getValue()"/>
<input type="button" value="Better" onclick="alternateGetValue()"/>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center" class="wide"><b>Time In</b></td>
<td align="center" class="wide"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody>
<template id="row">
<tr style="background-color:#8F8FBC;" class="data">
<td align="center"><div class="displayarea"></div></td>
<td align="center"><div class="displayarea1"></div></td>
<td align="center"><div class="displayarea2"></div></td>
<td align="center"><div class="displayarea3"></div></td>
<td align="center"><div class="displayarea4"></div></td>
</tr>
</template>
</tbody>
</table>

How to dynamically re-align elements of table when table size changes?

function ausgabe()
{
var array= new Array();
array.push(window.document.Rechner.Display2.value+
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign="right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
The input history is shown on the right.
Text aligned right.
I want there to be a default width, but if something longer is entered, the other entries have to be aligned to the new width.
<html>
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
<script type="text/javascript">
var equalsPressed = false;
function Check(Eingabe)
{
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var nur_das ="0123456789[]()-+*%/";
for (var i = 0; i < Eingabe.length; i++)
if (nur_das.indexOf(Eingabe.charAt(i))<0 ) return false;
return true;
}
function Ergebnis()
{
var z = document.getElementById("Historie");
z.style.display = "block";
equalsPressed = true;
var x = 0;
var y = 0;
if (Check(window.document.Rechner.Display.value) || equalsPressed)
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
x = eval(window.document.Rechner.Display.value);
window.document.Rechner.Display.value ="="+x;
}
function add(Zeichen)
{
if(equalsPressed)
{
window.document.Rechner.Display2.value = " ";
window.document.Rechner.Display.value = " ";
}
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
function backspace()
{
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++)
{
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe()
{
var array= new Array();
array.push(window.document.Rechner.Display2.value+
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign="right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
</script>
<style>
body{
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button{
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width:60px;
text-align:center;
font-family:System,sans-serif;
font-size:100%;
}
.ops{
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width:60px;
text-align:center;
font-family:System,sans-serif;
font-size:100%;
}
.button:hover{
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey,grey);;
}
.display{
width:100%;
text-align:right;
font-family:System,sans-serif;
font-size:100%;
}
#Historie{
background: linear-gradient(30deg,silver,white,grey);;
border: 5px outset;
float:left;
text-align:right;
}
#eins{
background: linear-gradient(30deg,silver, grey,DimGray);;
}
#zwei{
background: linear-gradient(90deg,silver, grey);;
}
#tabelle{
width: 300px;
height:235px;
float:left;
}
</style>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text"name="Display2"class="display"readonly>
<input type="text"name="Display"class="display"readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input
type="button"
class="button"
value=" 7 "
onClick="add('7')">
</td>
<td><input
type="button"
class="button"
value=" 8 "
onClick="add('8')">
</td>
<td><input
type="button"
class="button"
value=" 9 "
onClick="add('9')">
</td>
<td><input
type="button"
class="button"
value=" &#171 "
onClick="backspace()">
</td>
</tr>
<tr>
<td><input
type="button"
class="button"
value=" 4 "
onClick="add('4')">
</td>
<td><input
type="button"
class="button"
value=" 5 "
onClick="add('5')">
</td>
<td><input
type="button"
class="button"
value=" 6 "
onClick="add('6')">
</td>
<td><input
type="button"
class="ops"
value=" + "
onClick="add('+')">
</td>
</tr>
<tr>
<td><input
type="button"
class="button"
value=" 1 "
onClick="add('1')">
</td>
<td><input
type="button"
class="button"
value=" 2 "
onClick="add('2')">
</td>
<td><input
type="button"
class="button"
value=" 3 "
onClick="add('3')">
</td>
<td><input
type="button"
class="ops"
value=" - "
onClick="add('-')">
</td>
</tr>
<tr>
<td><input
type="button"
class="button"
value=" . "
onClick="add('.')">
</td>
<td><input
type="button"
class="button"
value=" 0 "
onClick="add('0')">
</td>
<td><input
type="button"
class="button"
value=" = "
onClick="Ergebnis();ausgabe()">
</td>
<td><input
type="button"
class="ops"
value=" * "
onClick="add('*')">
</td>
</tr>
<tr>
<td><input
type="button"
class="button"
value=" ( "
onClick="add('(')">
</td>
<td><input
type="button"
class="button"
value=" ) "
onClick="add(')')">
</td>
<td><input
type="reset"
class="button"
value=" C ">
</td>
<td><input
type="button"
class="ops"
value=" / "
onClick="add('/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie"id="Historie"hidden="true">
</div>
</body>
</html>

Is there a way to add the total of a div?

I am having trouble trying to add the total of a div from an array. I am trying to add the total miles for the input and put it in a table. I want to just add the miles together, not the flight numbers. I would also like to have an id set for it so that I can call on to the total miles in another section.
var FlightNumber = new Array();
var Miles = new Array();
function insert() {
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length] = FlightNumberValue;
Miles[Miles.length] = MilesValue;
}
function showFlightNumber() {
var content = "<b></b><br>";
for (var i = 0; i < FlightNumber.length; i++) {
content += FlightNumber[i] + "<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content = "<b></b><br>";
for (var i = 0; i < Miles.length; i++) {
content += Miles[i] + "<br>";
}
document.getElementById('display2').innerHTML = content;
}
table,
th,
td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles.
<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();"> <br>
<input type="button" value="Show miles" onclick="showMiles();"> <br>
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td>
<div id="display">
</div>
</td>
<td>
<div id="display2">
</div>
</td>
</tr>
<td>Total Miles:</td>
<td></td>
</table>
I was able to get the miles to total by putting an id on the total column. Then I was able to use the Miles array you created and just parse the string value to an int and total those values.
Please note this code is not very clean. When you insert a new flight you should really be inserting a new row, not break lines. There are javascript frameworks out there that make it really easy to iterate over arrays, e.g. AngularJs / Angular / React / Vue.js.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();"> <br>
<input type="button" value="Show miles" onclick="showMiles();"> <br>
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
</body>
</html>

I want to append my data below the table and search when user clicks in the product id field

I have created a table and I want to add the data below the table but data is being added at the top,
I have written a search property when user enters the product id the data should be shown and can't figure out where my code went wrong,
I want to add serch field to all the buttons should I write the code many times is there any solution?
$(document).ready(function() {
var url = "http://34.201.147.118:3001/getAllData";
$.getJSON(url, function(data) {
console.log(data);
//console.log("AllData")
var obj = data['AllData'];
//console.log(obj)
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>" +
"<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child"> tr</tr>');
}
});
});
function goodCall() {
$(document).ready(function() {
$("#id").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
}
body {
background-image: url("banner.jpg");
background-size: 100%;
}
#mytable {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
width: 100%;
}
#mytable td,
#customers th {
border: 1px solid #ddd;
padding: 8px;
}
#mytable tr:hover {
background-color: #ddd;
}
#mytable th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Page Content -->
<div style="margin-left:25%">
<h1 style="color:white;">TITLE DETAILS</h1>
<div class="w3-container" id="add">
<div class="" style="color:white;">
<form name="test_form" id="101">
<table class="table borderless">
<tr>
<th>Title Identifier</th>
</tr>
<tr>
<td style="border:none">
<b>PRODUCT ID</b>
<br>
<input type="text" id="id" style="color:black;" required></td>
<td style="border:none"></td>
<td style="border:none">
<b>PRODUCT TITLE</b>
<br><input type="text" id="title" style="color:black;" required></td>
</tr>
<tr>
<td style="border:none">
<br> <b>director </b>
<br> <input type="text" id="ter" style="color:black;" required>
</td>
<td style="border:none"></td>
<td style="border:none">
<b>producer</b>
<br> <input type="text" id="media" style="color:black;" required>
</td>
</tr>
</table>
</form>
<input type="button" onclick="goodCall()" value="Search" style="color:Red;">
<table id='mytable'>
<tr>
<th>ID</th>
<th>PRODUCTTITLE</th>
</tr>
<div>
<br><br>
</div>
</table>
</div>
</div>
</div>
Here you have a basic functional example https://jsfiddle.net/0Lvqcd8t/39/
You should change this:
var tr = "<tr>" +
"<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child"> tr</tr>');
for this:
var tr = "<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child">'+ tr+'</tr>');
In the first case you are creating <tr><tr class="child><td></td></tr> (first <tr> is wrong) and browser will render something like <tr>tr</tr><tr class='child'>empty</tr> also, tr var in first example is not interpreted as variable, so you should place it like +tr+. I've made a basic filter function at the end that works with id.

JS How to calculate the values of rows in a table?

For example, there is such a table, with cells FootballPlayers, Swimmers, BasketballPlayers and Sum, in which rows are added in turn, how i can count and record in the Total row how many football players, swimmers and basketball players are added?
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled=true;
}
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k=0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k=0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k=0;
}
var sum1 = (f1k+f2k+f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1=tbody.insertCell(0);
r1.innerHTML="";
var r2=tbody.insertCell(1);
r2.innerHTML=f1;
var r3=tbody.insertCell(2);
r3.innerHTML=f2;
var r4=tbody.insertCell(3);
r4.innerHTML=f3;
var r4=tbody.insertCell(4);
r4.innerHTML=sum1;
if(document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled=false;
}
}
#tg {border-collapse:collapse;border-spacing:0;}
#tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg .tg-yw4l{vertical-align:top}
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;" >Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e"></td>
<td class="tg-031e"></td>
<td class="tg-yw4l"></td>
<td class="tg-yw4l"></td>
</tr>
</table>
Here is an example, only total FootballPlayers
Step 1)
Add a class for FootballPlayers column when you add a row
Step 2)
Call total() javascript function while add a row and delete a row
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;" >Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l sum">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e total_fb_players"></td>
<td class="tg-031e total_summers"></td>
<td class="tg-yw4l total_bb_players"></td>
<td class="tg-yw4l total_sum"></td>
</tr>
</table>
<style>
#tg {border-collapse:collapse;border-spacing:0;}
#tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg .tg-yw4l{vertical-align:top}
</style>
<script>
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled=true;
}
total();
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k=0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k=0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k=0;
}
var sum1 = (f1k+f2k+f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1=tbody.insertCell(0);
r1.innerHTML="";
var r2=tbody.insertCell(1);
r2.classList.add('fb_players')
r2.innerHTML=f1;
var r3=tbody.insertCell(2);
r3.classList.add('summers')
r3.innerHTML=f2;
var r4=tbody.insertCell(3);
r4.classList.add('bb_players')
r4.innerHTML=f3;
var r5=tbody.insertCell(4);
r5.classList.add('sum')
r5.innerHTML=sum1;
if(document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled=false;
}
total();
}
function total() {
var fb_players = document.getElementsByClassName("fb_players");
var total_fb_players = 0;
for(var i = 0; i < fb_players.length; i++) {
var v = parseInt(fb_players[i].innerHTML);
if (isNaN(v)) {
v=0;
}
console.log(v);
total_fb_players += v;
}
console.log(total_fb_players);
var total_fb_players_html = document.querySelector(".total_fb_players");
total_fb_players_html.innerHTML=total_fb_players;
}
</script>
Add classes to your cells and ids to for each total column in your table and execute as follows
Snippet below
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled = true;
}
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k = 0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k = 0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k = 0;
}
var sum1 = (f1k + f2k + f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1 = tbody.insertCell(0);
r1.innerHTML = "";
var r2 = tbody.insertCell(1);
r2.innerHTML = f1;
r2.className = "football";
var r3 = tbody.insertCell(2);
r3.innerHTML = f2;
r3.className = "swimmer";
var r4 = tbody.insertCell(3);
r4.innerHTML = f3;
r4.className = "basketball";
var r4 = tbody.insertCell(4);
r4.innerHTML = sum1;
if (document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled = false;
}
var football_el = document.getElementsByClassName("football");
var swim_count_el = document.getElementsByClassName("swimmer");
var basketball_el = document.getElementsByClassName("basketball");
var list = [football_el, swim_count_el, basketball_el];
grand_sum = 0;
for (var y = 0; y < list.length; ++y) {
var sum = 0;
for (var x = 0; x < list[y].length; ++x) {
sum += Number(list[y][x].innerHTML);
}
if (y == 0) {
document.getElementById("total_footballers").innerHTML = sum;
grand_sum += sum;
} else if (y == 1) {
document.getElementById("total_swimmers").innerHTML = sum;
grand_sum += sum;
} else if (y == 2) {
document.getElementById("total_basketballers").innerHTML = sum;
grand_sum += sum;
}
} //end for
document.getElementById("grandtotal").innerHTML = grand_sum;
}
#tg {
border-collapse: collapse;
border-spacing: 0;
}
#tg td {
font-family: Arial, sans-serif;
font-size: 14px;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
}
#tg th {
font-family: Arial, sans-serif;
font-size: 14px;
font-weight: normal;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
}
#tg .tg-yw4l {
vertical-align: top
}
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;">Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e" id="total_footballers"></td>
<td class="tg-031e" id="total_swimmers"></td>
<td class="tg-yw4l" id="total_basketballers"></td>
<td class="tg-yw4l" id="grandtotal"></td>
</tr>
</table>

Categories