Need To Import HTML values From Google Sheets to Google WebApp - javascript

I'm working on the Search crud via Google webapp, I want to display the HTML design on front end via fetching it from Google sheets cells. Showing some examples in the screen shot
Google Sheet cell contains with HTML codes
The front end doesn't display the HTML design from the Google sheets but displaying the data with HTML code.
Here is my Script Code
main.html
</head>
<body>
<div class="container">
<div id="app"></div>
<!-- Content here -->
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<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/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
var data;
function loadView(options){
var id = typeof options.id === "undefined" ? "app" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html){
document.getElementById("app").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchinput = document.getElementById("searchinput").value.toString().toLowerCase().trim();
var searchWords = searchinput.split(/\s+/);
var searchColumns = [0,1,2,3,4,5,6,7];
// and or
var resultsArray = data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var l1Column = tr.querySelector(".L1");
var l2Column = tr.querySelector(".L2");
var l3Column = tr.querySelector(".L3");
var l4Column = tr.querySelector(".L4");
var l5Column = tr.querySelector(".L5");
var l6Column = tr.querySelector(".L6");
var l7Column = tr.querySelector(".L7");
var l8Column = tr.querySelector(".L8");
l1Column.textContent = r[0];
l2Column.textContent = r[1];
l3Column.textContent = r[2];
l4Column.textContent = r[3];
l5Column.textContent = r[4];
l6Column.textContent = r[5];
l7Column.textContent = r[6];
l8Column.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
function loadSearchView(){
loadView({func:"loadSearchView", callback: setDataForSearch});
}
window.addEventListener("load", loadSearchView);
function inputEventHandler(e){
if (e.target.matches("#searchinput")){
search();
}
}
document.getElementById("app").addEventListener("input",inputEventHandler);
</script>
</body>
</html>
search.html
<div class="form-group">
<input type="text" class="form-control" id="searchinput" placeholder="search...">
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Phone Number</th>
<th scope="col">Code</th>
<th scope="col">Country</th>
<th scope="col">City</th>
<th scope="col">Street</th>
</tr>
</thead>
<tbody id="searchResults">
</tbody>
</table>
<template id="rowTemplate">
<tr>
<td class="L1"></td>
<td class="L2"></td>
<td class="L3"></td>
<td class="L4"></td>
<td class="L5"></td>
<td class="L6"></td>
<td class="L7"></td>
<td class="L8"></td>
</tr>
</template>
serversidefunc.gs
function getDataForSearch(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("customer");
return ws.getRange(2, 1, ws.getLastRow(),8).getValues();
}
loadpartials.gs
function loadPartialHTML_(partial) {
const htmlServ = HtmlService.createTemplateFromFile(partial);
return htmlServ.evaluate().getContent();
}
function loadSearchView(){
return loadPartialHTML_("search");
}
I Hope my above post is clear.

How about the following modification for the function of search() in Javascript side?
From:
l1Column.textContent = r[0];
l2Column.textContent = r[1];
l3Column.textContent = r[2];
l4Column.textContent = r[3];
l5Column.textContent = r[4];
l6Column.textContent = r[5];
l7Column.textContent = r[6];
l8Column.textContent = r[7];
To:
l1Column.innerHTML = r[0];
l2Column.innerHTML = r[1];
l3Column.innerHTML = r[2];
l4Column.innerHTML = r[3];
l5Column.innerHTML = r[4];
l6Column.innerHTML = r[5];
l7Column.innerHTML = r[6];
l8Column.innerHTML = r[7];
Reference:
innerHTML

Related

Loading default text string to a table by javascript

I’ve made a form where I want the users to be able to add books (title, author, isbn).
<fieldset>
<legend>Bokdata</legend>
<label for="txtBookTitle">Tittel</label>
<input id="txtBookTitle" type="text" value="">
<label for="txtBookAuthor">Forfatter</label>
<input id="txtBookAuthor" type="text" value="">
<label for="txtBookISBN">ISBN</label>
<input id="txtBookISBN" type="text" value="">
<p>
<button onclick="addBookClick()">Legg til</button>
</p>
</fieldset>
The books will appear in this table:
<table border="2">
<thead>
<tr>
<th colspan="3">
Min bokliste
</th>
</tr>
<tr>
<th>Tittel</th>
<th>Forfatter</th>
<th>ISBN</th>
</tr>
</thead>
<tbody id="tblBodyList">
</tbody>
<tfoot id="tblSummary">
</tfoot>
</table>
Adding books by using the input-fields is done by this function:
function addBookClick(){
//Input fra skjemaet
var txtBookTitle = document.getElementById("txtBookTitle").value;
var txtBookAuthor = document.getElementById("txtBookAuthor").value;
var txtBookISBN = document.getElementById("txtBookISBN").value;
// Lag html-tabell
// 0 = tabell 1
var table = document.getElementsByTagName("table")[0];
// Legg til ny rad nederst i tabellen. (0) = øverste rad i tabellen.
var newRow = table.insertRow(table.rows.length);
// Legg til celler i tabellen
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
// Legg til values i cellene
cel1.innerHTML = txtBookTitle;
cel2.innerHTML = txtBookAuthor;
cel3.innerHTML = txtBookISBN;
}
I’m trying to insert some text into a table without html, but by javascript instead. The easiest would of course be to write the text in the table, but this is a school assignment, and I’m not allowed to do that. Getting help is allowed. I hope I’m close to something, but I could really use some advice. I’ve tried the last two days to get a grip on this:
var txtBookTitle = document.getElementById("txtBookTitle");
var txtBookAuthor = document.getElementById("txtBookAuthor");
var txtBookISBN = document.getElementById("txtBookISBN");
var tblBodyList = document.getElementById("tblBodyList");
var books = [];
var defaultBooks =
"Judo Unleashed,Neil Ohlenkamp,0-07-147534-6\n"+
"Kodokan Judo,Jigoro Kano,0-87011-681-9\n"+
"Olympic Judo,Neil Adams,0-7207-1735-3";
var book = {
title: "txtBookTitle",
author: "txtBookAuthor",
ISBN: "txtBookISBN"
};
function createBook(title, author, ISBN){
var Book = {};
Book.title = title;
Book.author = author;
Book.ISBN = ISBN;
books.push(Book);
return Book
}
var judo = "";
var kodokan = "";
var olympic = "";
function loadDefaultBooks(){
judo = createBook("Judo Unleashed", "Neil Ohlenkamp", "0-07-147534-6");
kodokan = createBook("Kodokan Judo", "Jigoro Kano", "0-87011-681-9");
olympic = createBook("Olympic Judo" , "Neil Adams" , "0-7207-1735-3");
listBooks();
}
In your case you are not calling loadDefaultBooks. Also the function createBook is not making any sense. You can use the same function addBookClick and pass argument.
This line var txtBookTitle = a || document.getElementById("txtBookTitle").value; when a has a value consider that value, other on click of button a will be undefined. In that case consider the value from the input text
function addBookClick(a, b, c) {
//Input fra skjemaet
var txtBookTitle = a || document.getElementById("txtBookTitle").value;
var txtBookAuthor = b || document.getElementById("txtBookAuthor").value;
var txtBookISBN = c || document.getElementById("txtBookISBN").value;
// Lag html-tabell
// 0 = tabell 1
var table = document.getElementsByTagName("table")[0];
// Legg til ny rad nederst i tabellen. (0) = øverste rad i tabellen.
var newRow = table.insertRow(table.rows.length);
// Legg til celler i tabellen
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
// Legg til values i cellene
cel1.innerHTML = txtBookTitle;
cel2.innerHTML = txtBookAuthor;
cel3.innerHTML = txtBookISBN;
}
function loadDefaultBooks() {
addBookClick("Judo Unleashed", "Neil Ohlenkamp", "0-07-147534-6");
addBookClick("Kodokan Judo", "Jigoro Kano", "0-87011-681-9");
addBookClick("Olympic Judo", "Neil Adams", "0-7207-1735-3");
}
loadDefaultBooks()
<fieldset>
<legend>Bokdata</legend>
<label for="txtBookTitle">Tittel</label>
<input id="txtBookTitle" type="text" value="">
<label for="txtBookAuthor">Forfatter</label>
<input id="txtBookAuthor" type="text" value="">
<label for="txtBookISBN">ISBN</label>
<input id="txtBookISBN" type="text" value="">
<p>
<button onclick="addBookClick()">Legg til</button>
</p>
</fieldset>
<table border="2">
<thead>
<tr>
<th colspan="3">
Min bokliste
</th>
</tr>
<tr>
<th>Tittel</th>
<th>Forfatter</th>
<th>ISBN</th>
</tr>
</thead>
<tbody id="tblBodyList">
</tbody>
<tfoot id="tblSummary">
</tfoot>
</table>

Why wont my jsp page show all the objects from my angularjs list in ng-repeat?

JSP
<table class="countrys" data-name="tableProductsBuy">
<tr bgcolor="lightgrey">
<th>Product ID</th>
<th>Product Name</th>
<th>In Store</th>
</tr>
<tr data-ng-repeat="p in finalList"
data-ng-click="selectObject(p, $index);"
data-ng-class="getSelectedObject(p);">
<td>{{p.product.productId}}</td>
<td>{{p.product.productName}}</td>
<td>{{p.unitsOutStore}}</td>
</tr>
</table>
<button data-ng-click="buyIt()">Add to Shopping Cart</button>
controller
$scope.getSelectedObject = function(object) {
if ($scope.selectedObject.product.productId != undefined) {
if ($scope.selectedObject.product.productId == object.product.productId) {
return "selected";
}
}
return "";
};
$scope.selectObject = function(object, index){
$scope.selectedObject = object;
}
$scope.finalList = [];
$scope.theListB = [];
$scope.counter = 0;
$scope.priceOfProducts = 0;
$scope.buyIt = function(){
if ($scope.selectedProduct.unitsInStore>0){
$scope.selectedProduct.unitsInStore--;
$scope.theListB.push($scope.selectedProduct);
$scope.priceOfProducts += $scope.selectedProduct.pricePerUnit;
}else{
alert("The product ID:" + $scope.selectedProduct.productId +"\n" +
"With the name:" + $scope.selectedProduct.productName + "\n"
+"Is out of stock!");
}
$scope.showList();
}
$scope.showList=function(){
$scope.finalList = [];
angular.forEach($scope.theListB, function(productFromListB, key){
var go = true;
angular.forEach($scope.allSProducts, function(productFromStores, key){
if(productFromListB.productId == productFromStores.productId){
// if(go){
$scope.object.product = productFromListB;
$scope.object.unitsOutStore = productFromStores.unitsInStore - productFromListB.unitsInStore;
$scope.object.maxNumber = productFromStores.unitsInStore;
$scope.finalList.push($scope.object);
go = false;
// }
}
});
});
}
so in the end, i got the function $scope.showList()
there i have theListB filed with my 10 or more objects
that data i modify and add to finalList with this line:
$scope.finalList.push($scope.object);
but on the jsp page, it only shows the last added object in the table row
in ng-repeat...
any sugestions?
Here a pic
enter image description here

Color changes based on what number is listed issue

I wrote an if statement that says if the number is < 50 the background color is red. If the number is 51-74 it is orange and if it is 75 or up it's green. But the colors aren't changing based on the value and I'm not sure why.
Here's the site in action: http://www.andrewhnovak.com/test/index.html
Here's the code
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Site Demo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="css/header.css" rel="stylesheet" type="text/css">
<link href="css/mainPage.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row">
</div>
</div><!--
</div>
</div>
</div>
-->
<div class="container">
<div class='underHeader'></div>
</div>
<div class="container">
<div class='whiteBox'>
<div class='newProducts'></div>
<div id="frontPage">
<table class="table table-bordered" id="tablehere">
<thead>
<tr>
</tr>
<tr>
<th data-field="id">item<div id="Row1Rating">62</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row2Rating">55</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row3Rating">77</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row4Rating">66</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row5Rating">88</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row6Rating">22</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row7Rating">22</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row8Rating">22</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row9Rating">22</div></th>
</tr>
<tr>
<th data-field="id">item<div id="Row10Rating">22</div></th>
</tr>
<tr>
<div id="link">Test showing app.js is connected</div>
</tr>
</thead>
</table>
</div>
</div>
</div>
<footer></footer>
<script src="js/jquery-1.10.1.min.js" type="text/javascript"></script> <!--<script src="js/jquery.easing-1.3.js"></script>-->
<script src="js/bootstrap.js"></script> <script src="js/menu.js"></script>
<script src="js/app.js" type="text/javascript"></script>
</body>
</html>
JS
$(document).ready(function () {
$('#link').click(function(e) {
e.preventDefault();// prevent the default anchor functionality
$('#frontPage').hide();
frontPageRatings();
});
function frontPageRatings(){
var rowValue1 = document.getElementByID("Row1Rating");
var Value1 = parseInt(rowValue1.innerHTML);
var rowValue2 = document.getElementByID("Row2Rating");
var Value2 = parseInt(rowValue2.innerHTML);
var rowValue3= document.getElementByID("Row3Rating");
var Value3 = parseInt(rowValue3.innerHTML);
var rowValue4 = document.getElementByID("Row4Rating");
var Value4 = parseInt(rowValue4.innerHTML);
var rowValue5 = document.getElementByID("Row5Rating");
var Value5 = parseInt(rowValue5.innerHTML);
var rowValue6 = document.getElementByID("Row6Rating");
var Value6 = parseInt(rowValue6.innerHTML);
var rowValue7 = document.getElementByID("Row7Rating");
var Value7 = parseInt(rowValue7.innerHTML);
var rowValue8 = document.getElementByID("Row8Rating");
var Value8 = parseInt(rowValue7.innerHTML);
var rowValue9 = document.getElementByID("Row9Rating");
var Value9 = parseInt(rowValue7.innerHTML);
var rowValue10 = document.getElementByID("Row10Rating");
var Value10 = parseInt(rowValue7.innerHTML);
if(Value1<50){
rowValue1.style.backgroundColor = '#900000';
}
else if(Value1 >49 && Value1 <75){
rowValue1.style.backgroundColor = '#FF9933';
}
else if(Value1>74){
rowValue1.style.backgroundColor = '#00CC00';
}
if(Value2<50){
rowValue2.style.backgroundColor = '#900000';
}
else if(Value2 >49 && Value2 <75){
rowValue2.style.backgroundColor = '#FF9933';
}
else if(Value2>74){
rowValue2.style.backgroundColor = '#00CC00';
}
if(Value3<50){
rowValue3.style.backgroundColor = '#900000';
}
else if(Value3 >49 && Value3 <75){
rowValue3.style.backgroundColor = '#FF9933';
}
else if(Value3>74){
rowValue3.style.backgroundColor = '#00CC00';
}
if(Value4<50){
rowValue4.style.backgroundColor = '#900000';
}
else if(Value4 >49 && Value4 <75){
rowValue4.style.backgroundColor = '#FF9933';
}
else if(Value4>74){
rowValue4.style.backgroundColor = '#00CC00';
}
if(Value5<50){
rowValue5.style.backgroundColor = '#900000';
}
else if(Value5 >49 && Value5 <75){
rowValue5.style.backgroundColor = '#FF9933';
}
else if(Value5>74){
rowValue5.style.backgroundColor = '#00CC00';
}
if(Value6<50){
rowValue6.style.backgroundColor = '#900000';
}
else if(Value6 >49 && Value6 <75){
rowValue6.style.backgroundColor = '#FF9933';
}
else if(Value6>74){
rowValue6.style.backgroundColor = '#00CC00';
}
if(Value7<50){
rowValue7.style.backgroundColor = '#900000';
}
else if(Value7 >49 && Value7 <75){
rowValue7.style.backgroundColor = '#FF9933';
}
else if(Value7>74){
rowValue7.style.backgroundColor = '#00CC00';
}
}
});
You can drastically simplify your code by adding the same class (for example rating) to each element that you want to color based on the value.
Then in jQuery you can query for all elements with the class rating, and interate over them.
Your javascript will then look something like this:
jQuery(document).ready(function ($) {
$('.rating').each(function(i, el) {
var value = parseInt($(el).html(), 10);
var color = getColor( value );
$(el).css('background', color);
});
function getColor( value ) {
var color = '#00CC00'; // value bigger than 74
if(value < 50){
color = '#900000';
} else if(value > 49 && value < 75){
color = '#FF9933';
}
return color;
}
});
Working example:
http://jsfiddle.net/5yrdgj7h/1/
use this
do not have to write much for a simple function,
I modified the code and have reduced drastically.
$(document).ready(function () {
$('#link').click(function(e) {
e.preventDefault();// prevent the default anchor functionality
$('#frontPage').hide();
frontPageRatings();
});
function frontPageRatings(){
function getFirstCLS(elem){
return document.getElementsByClassName(elem)[0];
}
function getHTML(CLASS){
return parseInt(getFirstCLS(CLASS).innerHTML, 10);
}
function setCOLOR(CLASS, color){
getFirstCLS(CLASS).style.backgroundColor = color;
}
function ifELSE(elem){
if(getHTML(elem)<50){
setCOLOR(elem, '#900000');
} else if(getHTML(elem) >49 && getHTML(elem) <75){
setCOLOR(elem, '#FF9933');
} else if(getHTML(elem)>74){
setCOLOR(elem, '#00CC00');
}
}
ifELSE("Row1Rating");
ifELSE("Row2Rating");
ifELSE("Row3Rating");
ifELSE("Row4Rating");
ifELSE("Row5Rating");
ifELSE("Row6Rating");
ifELSE("Row7Rating");
ifELSE("Row8Rating");
ifELSE("Row9Rating");
ifELSE("Row10Rating");
}
});
You should change all of your div elements to use id attributes instead of class attributes and then use getElementById to access those elements. For example:
<th data-field="id">item<div id="Row2Rating">55</div></th>
and then in the javascript:
var rowValue2 = document.getElementById("Row2Rating");
A class is used to describe a group of similar elements to style them all the same way, and uses getElementsByClassName to locate all of the elements that share the class. An id should be a unique identifier and uses getElementById to select that unique element.

update html table with data from SQL database table in cshtml page

#{
var db = Database.Open("HEMS");
var LoadDevCmd = "SELECT * FROM " + App.UserMeterID;
var DevQuery = db.Query(LoadDevCmd);
foreach (var row in DevQuery)
{
var DevType = row.DeviceType;
var LoadType = row.Device_LoadType;
string Loc = row.Location;
var MAC = row.MACaddress;
var D_Status = row.DeviceStatus;
var myLoc = "";
if (Loc == null)
{
myLoc = "XLoc";
}
else
{
switch (Loc)
{
case "Living Room":
myLoc = "LivingRoom";
break;
case "Bedroom":
myLoc = "Bedroom";
break;
case "Bathroom":
myLoc = "Bathroom";
break;
case "Dining Room":
myLoc = "DiningRoom";
break;
case "Kitchen":
myLoc = "Kitchen";
break;
case "Balcony":
myLoc = "Balcony";
break;
case "Others":
myLoc = "Others";
break;
}
}
}
<body>
<table id="XLoc">
<tr>
<th align="left">Unknown Location</th>
</tr>
</table>
<table id="LivingRoom">
<tr>
<th align="left">Living Room</th>
</tr>
</table>
<table id="Bedroom">
<tr>
<th align="left">Bedroom</th>
</tr>
</table>
<table id="Bathroom">
<tr>
<th align="left">Bathroom</th>
</tr>
</table>
<table id="DiningRoom">
<tr>
<th align="left">Dining Room</th>
</tr>
</table>
<table id="Kitchen">
<tr>
<th align="left">Kitchen</th>
</tr>
</table>
<table id="Balcony">
<tr>
<th align="left">Balcony</th>
</tr>
</table>
<table id="Others">
<tr>
<th align="left">Others</th>
</tr>
</table>
</body>
<script>
function displayDev(id, MAC) {
var table = document.getElementById(id);
var row = table.insertRow(-1);
var cell = row.insertCell(-1);
cell.innerHTML = "MacAddress: " + MAC ;
}
</script>
I'm trying update my html tables in tag as shown above with the script function( displayDev(id, MAC)}. May I know how may I call the script function in the #{}?
I've tried the page.ClientScriptManager.RegisterStartupScript(); but I always get null page which cause the NullReferenceException error, may I know how should I fix it?
Try #Html.Raw("displayDev(" + myLoc + ")")

Javascript: Get number values from dynamic Javascript table and Input box then do calculation

This is for a project in progress. I need to create a calculation that will grab the number from the 'total' row in the 'off column' in the table, then minus this from the starting balance that is defined in the input box. The result of this calculation then needs to be displayed in an alert box when the submit button is clicked.
It's a bit beyond me and if anyone could point me in the right direction I would be grateful.
HTML:
<!DOCTYPE html>
<html>
<head>
<h1><em>EXPENSES CALCULATOR</em></h1>
<link rel="stylesheet" type="text/css" href="tt.css"/>
</head>
<body>
<p id="balance">Starting balance (£)<input type="number"></p>
<p>
<input type="button" id="addNewRow" value="Add new row">
<input type="button" onClick="window.print()" value="Print your purchases"/>
</p>
<table id="breakdowntable">
<tr>
<th>Payment type</th>
<th>Off</th>
<th>To come off</th>
<th>Total</th>
</tr>
<tr id="card">
<th>Card Payment</th>
<td>0</td>
<td>0</td>
<td id="cardtotal">0</td>
</tr>
<tr id="cash">
<th>Cash Payment</th>
<td>0</td>
<td>0</td>
<td id="cashtotal">0</td>
</tr>
<tr id="other">
<th>Other Payment</th>
<td>0</td>
<td>0</td>
<td id="othertotal">0</td>
</tr>
<tr id="total">
<th>Total</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<table id="purchases"> </table>
<p><input type="Submit" id="submit" onclick='alert(money_to_number())'> </p>
<script type="text/javascript" src="tt.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"> </script>
</body>
</html>
JavaScript:
var doc = document;
function calculateAmount() {
var purchases = doc.getElementById('purchases');
var purchasesRows = purchases.rows;
var typeValue = {'CP' : [0,0], 'CA' : [0,0], 'OP' : [0,0]};
for (var i = 0, purchasesRowsLength = purchasesRows.length, pytType, inputs, isItOffInput, isItOff; i < purchasesRowsLength; ++i) {
pytType = purchasesRows[i].getElementsByTagName('SELECT')[0];
inputs = purchasesRows[i].getElementsByTagName('INPUT');
isItOffInput = inputs[0];
isItOff = inputs[inputs.length - 1].checked ? 0 : 1;
typeValue[pytType.value][isItOff] += isItOffInput.value - 0;
}
var total = [0, 0];
var cardCells = doc.getElementById('card').cells;
cardCells[1].innerHTML = typeValue['CP'][0];
total[0] += typeValue['CP'][0];
cardCells[2].innerHTML = typeValue['CP'][1];
total[1] += typeValue['CP'][1];
cardCells[3].innerHTML = typeValue['CP'][0] + typeValue['CP'][1];
var cashCells = doc.getElementById('cash').cells;
cashCells[1].innerHTML = typeValue['CA'][0];
total[0] += typeValue['CA'][0];
cashCells[2].innerHTML = typeValue['CA'][1];
total[1] += typeValue['CA'][1];
cashCells[3].innerHTML = typeValue['CA'][0] + typeValue['CA'][1];
var otherCells = doc.getElementById('other').cells;
otherCells[1].innerHTML = typeValue['OP'][0];
total[0] += typeValue['OP'][0];
otherCells[2].innerHTML = typeValue['OP'][1];
total[1] += typeValue['OP'][1];
otherCells[3].innerHTML = typeValue['OP'][0] + typeValue['OP'][1];
var totalCells = doc.getElementById('total').cells;
totalCells[1].innerHTML = total[0];
totalCells[2].innerHTML = total[1];
totalCells[3].innerHTML = total[0] + total[1];
}
function addNewRow() {
var purchases = doc.getElementById('purchases');
var row = purchases.insertRow(purchases.rows.length);
var pytTypeCell = row.insertCell(0);
var type = [['CP', 'Paid by Card £'], ['CA', 'Paid with Cash £'], ['OP', 'Other Payment type £']];
var pytType = doc.createElement('SELECT');
for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) {
option = doc.createElement('OPTION');
option.value = type[i][0];
option.innerHTML = type[i][1];
pytType.appendChild(option);
}
pytType.onchange = calculateAmount;
var pytTypeLabel = doc.createElement('LABEL');
pytTypeLabel.innerHTML = 'Type';
pytTypeLabel.appendChild(pytType);
pytTypeCell.appendChild(pytTypeLabel);
var isItOffInput = doc.createElement('INPUT');
isItOffInput.type = 'number';
isItOffInput.onkeyup = calculateAmount;
pytTypeCell.appendChild(isItOffInput);
var descriptInputCell = row.insertCell(1);
var descriptInput = doc.createElement('INPUT');
descriptInput.type = 'number';
var descriptLabel = doc.createElement('LABEL');
descriptLabel.innerHTML = 'Description';
descriptLabel.appendChild(descriptInput);
descriptInputCell.appendChild(descriptLabel);
var dateInputCell = row.insertCell(2);
var dateInput = doc.createElement('INPUT');
dateInput.type = 'date';
var dateLabel = doc.createElement('LABEL');
dateLabel.innerHTML = 'Payment Date';
dateLabel.appendChild(dateInput);
dateInputCell.appendChild(dateLabel);
var isItOffCheckBoxCell = row.insertCell(3);
var isItOffCheckBox = doc.createElement('INPUT');
isItOffCheckBox.type = 'checkbox';
isItOffCheckBox.onclick = calculateAmount;
var isItOffLabel = doc.createElement('LABEL');
isItOffLabel.appendChild(isItOffCheckBox);
isItOffLabel.appendChild(document.createTextNode('Is it Off?'));
isItOffCheckBoxCell.appendChild(isItOffLabel);
}
doc.getElementById('addNewRow').onclick = addNewRow;
window.onload = function() {
addNewRow();
};
Here it is in a jsFiddle: http://jsfiddle.net/jfBAJ/
You need to give ids to the elements you want to find later. I gave your starting balance input the id "starting_balance" and I gave your grand total TD the id of "grand_total" then wrote the following onSubmit:
document.getElementById("submit").onclick = onSubmit
function onSubmit(){
var starting = document.getElementById("starting_balance").value;
var grandTotal = document.getElementById("grand_total").innerHTML;
var finalBalance =parseFloat(grandTotal||0) + parseFloat(starting||0);
alert(finalBalance);
}
This alerts the new total + the starting balance.

Categories