I need some help in explaining to me how I can save data from dynamically added inputs to my SQL database table.
What I am doing is creating an online quote / invoice web site whereby one can create the quote and then save the data or print to pdf. (I am currently working on the "save the data" bit :-) )
So by adding the input fields (text boxes) I use a java script as per below:
(function (document) {
var
head = document.head = document.getElementsByTagName('head')[0] || document.documentElement,
elements = 'article aside audio bdi canvas data datalist details figcaption figure footer header
hgroup mark meter nav output picture progress section summary time video x'.split(' '),
elementsLength = elements.length,
elementsIndex = 0,
element;
while (elementsIndex < elementsLength) {
element = document.createElement(elements[++elementsIndex]);
}
element.innerHTML = 'x<style>' +
'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
'audio[controls],canvas,video{display:inline-block}' +
'[hidden],audio{display:none}' +
'mark{background:#FF0;color:#000}' +
'</style>';
return head.insertBefore(element.lastChild, head.firstChild);
})(document);
(function (window, ElementPrototype, ArrayPrototype, polyfill) {
function NodeList() { [polyfill] }
NodeList.prototype.length = ArrayPrototype.length;
ElementPrototype.matchesSelector = ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.oMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
function matchesSelector(selector) {
return ArrayPrototype.indexOf.call(this.parentNode.querySelectorAll(selector), this) > -1;
};
ElementPrototype.ancestorQuerySelectorAll = ElementPrototype.ancestorQuerySelectorAll ||
ElementPrototype.mozAncestorQuerySelectorAll ||
ElementPrototype.msAncestorQuerySelectorAll ||
ElementPrototype.oAncestorQuerySelectorAll ||
ElementPrototype.webkitAncestorQuerySelectorAll ||
function ancestorQuerySelectorAll(selector) {
for (var cite = this, newNodeList = new NodeList; cite = cite.parentElement;) {
if (cite.matchesSelector(selector)) ArrayPrototype.push.call(newNodeList, cite);
}
return newNodeList;
};
ElementPrototype.ancestorQuerySelector = ElementPrototype.ancestorQuerySelector ||
ElementPrototype.mozAncestorQuerySelector ||
ElementPrototype.msAncestorQuerySelector ||
ElementPrototype.oAncestorQuerySelector ||
ElementPrototype.webkitAncestorQuerySelector ||
function ancestorQuerySelector(selector) {
return this.ancestorQuerySelectorAll(selector)[0] || null;
};
})(this, Element.prototype, Array.prototype);
function generateTableRow() {
var emptyColumn = document.createElement('tr');
emptyColumn.innerHTML = '<td><a class="cut" title="Remove Item">-</a><span contenteditable></span>
</td>' +
'<td><span contenteditable></span></td>' +
'<td><span data-prefix>₹</span><span contenteditable>0.00</span></td>' +
'<td><span contenteditable>1</span></td>' +
'<td><span data-prefix>₹</span><span>0.00</span></td>';
return emptyColumn;
}
function parseFloatHTML(element) {
return parseFloat(element.innerHTML.replace(/[^\d\.\-]+/g, '')) || 0;
}
function parsePrice(number) {
return number.toFixed(2).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,');
}
function updateNumber(e) {
var
activeElement = document.activeElement,
value = parseFloat(activeElement.innerHTML),
wasPrice = activeElement.innerHTML == parsePrice(parseFloatHTML(activeElement));
if (!isNaN(value) && (e.keyCode == 38 || e.keyCode == 40 || e.wheelDeltaY)) {
e.preventDefault();
value += e.keyCode == 38 ? 1 : e.keyCode == 40 ? -1 : Math.round(e.wheelDelta * 0.025);
value = Math.max(value, 0);
activeElement.innerHTML = wasPrice ? parsePrice(value) : value;
}
updateInvoice();
}
function updateInvoice() {
var total = 0;
var cells, price, total, a, i;
for (var a = document.querySelectorAll('table.inventory tbody tr'), i = 0; a[i]; ++i) {
// get inventory row cells
cells = a[i].querySelectorAll('span:last-child');
// set price as cell[2] * cell[3]
price = parseFloatHTML(cells[2]) * parseFloatHTML(cells[3]);
// add price to total
total += price;
// set row total
cells[4].innerHTML = price;
}
// get label cells
label_cells = document.querySelectorAll('table.balance th span:last-child');
tax_rate = label_cells[1].innerHTML / 100;
// get balance cells
cells = document.querySelectorAll('table.balance td:last-child span:last-child');
// set total
cells[0].innerHTML = total;
// set tax
cells[1].innerHTML = parsePrice(total * tax_rate);
// set balance and meta balance
cells[2].innerHTML = document.querySelector('table.meta tr:last-child td:last-child span:last-
child').innerHTML = parsePrice(total + parseFloatHTML(cells[1]));
var prefix = document.querySelector('#prefix').innerHTML;
for (a = document.querySelectorAll('[data-prefix]'), i = 0; a[i]; ++i) a[i].innerHTML = prefix;
for (a = document.querySelectorAll('span[data-prefix] + span'), i = 0; a[i]; ++i) if
(document.activeElement != a[i]) a[i].innerHTML = parsePrice(parseFloatHTML(a[i]));
}
function onContentLoad() {
updateInvoice();
var
input = document.querySelector('input'),
image = document.querySelector('img');
function onClick(e) {
var element = e.target.querySelector('[contenteditable]'), row;
element && e.target != document.documentElement && e.target != document.body && element.focus();
if (e.target.matchesSelector('.add')) {
document.querySelector('table.inventory tbody').appendChild(generateTableRow());
}
else if (e.target.className == 'cut') {
row = e.target.ancestorQuerySelector('tr');
row.parentNode.removeChild(row);
}
updateInvoice();
}
function onEnterCancel(e) {
e.preventDefault();
image.classList.add('hover');
}
function onLeaveCancel(e) {
e.preventDefault();
image.classList.remove('hover');
}
function onFileInput(e) {
image.classList.remove('hover');
var
reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
}
function onFileLoad(e) {
var data = e.target.result;
image.src = data;
}
if (window.addEventListener) {
document.addEventListener('click', onClick);
document.addEventListener('mousewheel', updateNumber);
document.addEventListener('keydown', updateNumber);
document.addEventListener('keydown', updateInvoice);
document.addEventListener('keyup', updateInvoice);
input.addEventListener('focus', onEnterCancel);
input.addEventListener('mouseover', onEnterCancel);
input.addEventListener('dragover', onEnterCancel);
input.addEventListener('dragenter', onEnterCancel);
input.addEventListener('blur', onLeaveCancel);
input.addEventListener('dragleave', onLeaveCancel);
input.addEventListener('mouseout', onLeaveCancel);
input.addEventListener('drop', onFileInput);
input.addEventListener('change', onFileInput);
}
}
window.addEventListener && document.addEventListener('DOMContentLoaded', onContentLoad);
function serial_file() {
document.getElementById("serial").value = Date.now();
}
function un_serial_file() {
document.getElementById("serial").value = "";
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = dd + '/' + mm + '/' + yyyy;
today_form = yyyy + '-' + dd + '-' + mm + ' ';
var serial = Date.now();
function myprint() {
window.print();
}
And on my "NewQuote.aspx" Page I have this:
<div class="container-fluid">
<div style="display: inline-block; float: left;">
<asp:DropDownList runat="server" ID="drpClientSelect" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList><br />
<br />
<asp:Label runat="server" Text="First Name" ID="lblFirstName"></asp:Label><br />
<asp:Label runat="server" Text="Last Name" ID="lblLastName"></asp:Label><br />
<asp:Label runat="server" Text="Company Name" ID="lblCompanyName"></asp:Label><br />
<asp:Label runat="server" Text="Address" ID="lblAddress"></asp:Label><br />
<asp:Label runat="server" Text="Email" ID="lblEmail"></asp:Label><br />
<asp:Label runat="server" Text="Contact Number" ID="lblContactNumber"></asp:Label><br />
<asp:Label runat="server" Text="Web Site Address" ID="lblWebsite"></asp:Label><br />
</div>
<br />
<div>
<table class="meta" id="top_data_table">
<tbody>
<tr class="" id="invoice_number_row">
<th class="bold"><span class="invoice" id="invoice">Invoice #</span></th>
<td>
<input type="text" name="fname" /></td>
</tr>
<tr id="daterow">
<th class="bold"><span class="date" id="date">Date</span></th>
<td><span>
<input type="date" id="theDate" /></span></td>
</tr>
<tr class="" id="total_block">
<th class="bold"><span class="amount" id="amount">Ammout</span></th>
<td><span id="prefix">R</span><span></span></td>
</tr>
</tbody>
</table>
</div>
</div>
<hr />
<br />
<div class="min_height">
<table class="inventory">
<thead>
<tr>
<th class="bold">
<span class="item" id="item">Item</span>
</th>
<th class="bold">
<span class="description" id="description">Description</span>
</th>
<th class="bold">
<span class="rate" id="rate">Rate</span>
</th>
<th class="bold">
<span class="quantity" id="quantity">Quantity</span>
</th>
<th class="bold">
<span class="price" id="price">Price</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a class="cut" title="Remove Item">-</a>
<span contenteditable="true"></span>
</td>
<td>
<span contenteditable="true"></span>
</td>
<td>
<span data-prefix="">R</span>
<span contenteditable="true">0.00</span>
</td>
<td>
<span contenteditable="true">1</span>
</td>
<td>
<span data-prefix="">R</span><span>0.00</span>
</td>
</tr>
</tbody>
</table>
<a class="add noprint" title="Add Item">+</a>
<div class="left_btn">
<button class="mah_btn" onclick="myprint()">Print</button>
<button class="mah_btn" onclick="window.location.reload()">Reset</button>
</div>
<div class="right_tax">
<table class="balance" id="balance">
<tbody>
<tr>
<th class="bold">
<span class="subtotal" id="subtotal">Subtotal</span>
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
<tr>
<th class="bold">
<span class="tax" id="tax" contenteditable="true">Include VAT </span>
<span contenteditable="true">0</span>%
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
<tr>
<th class="bold">
<span class="total" id="total">Total</span>
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
So the end results looks like this (with the CSS ofcourse :-) )
enter image description here
As you can see you can add a new row and insert some data. If you hover over the input line a "minues" sign will popup where you can delete that row. It will also automatically multiply and add the necassary fields to display total amount. All of this works great, but I now want to save it to my SQL database table. For this I have created the table and looks like this:
CREATE TABLE [dbo].[tbl_newQuotes] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] NVARCHAR (MAX) NULL,
[Description] NVARCHAR (MAX) NULL,
[Rate] NVARCHAR (MAX) NULL,
[Quantity] NVARCHAR (MAX) NULL,
[Price] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
And as you can guess this is where I am stuck :-( No I have saved form data before which is realtively simple by supllying the TextBox ID and values and save that to the database. But this is a complete different ball game and am not sure on how to achieve that.
I have covered most things in the question, but if you require more info please let me know.
EDIT
If there is a simpler way maybe to achieve this I am all ears :-) Maybe a tutorial on creating an invoice / quotation web forms app?
I have tried now again and can't seem to figure it out :-(
Thanks
I want you to approach it in a different way by using a GridView control.
When you click the "+" button, you save a row you have added into the table; bind the gridview taking records from the table; and display the rows including the necessary fields calculated like total amount.
There is another way by using a DataTable. Create a DataTable and save those rows to the DataTable. Then put another button called "Save" which makes those records in the DataTable saved into the Table. After saving and refreshing the screen, bring the records saved to the DataTable to display the rows on the screen.
Provided you are using jquery, it is possible to do by creating the JSON object of the inputs you added.
Create JSON object for multiple rows
Make an ajax call to pass the JSON object to web method.
Populate datatable with parsing the JSON object
Create user defined table Type in SQL for the datatable we wish to pass.
Pass datatable to Stored procedure and in SP process the data as you want.
Because I'm too lazy to calculate every time I decided to make a calculator with jquery.
For some reason it's not working and I don't know why so I'm here to ask you guys for help.
Here's a jsfiddle link
Damage Formula:
AbaseEq: Damage Range of weapon (e.g: 800~1000)
up difference: weapon up- armor up (e.g: 5-3:2 -> up difference:2 -> 15% if difference was 1 it would be 10%)
Aeq: AbaseEq(1+up difference in %)
Codes:
<table>
<tr>
<td>
<label>Base Attack (Without any equipment equipped): </label>
</td>
<td>
<input placeholder="e.g: 290" id="abase">
</td>
</tr>
<tr>
<td>
<label>Weapon Attack Range: </label>
</td>
<td>
<input placeholder="e.g: 800-1000" id="abaseeq">
</td>
</tr>
<tr>
<td>
<label>Weapon + ?</label>
</td>
<td>
<input placeholder="e.g: 9" id="weapon+">
</td>
</tr>
<tr>
<td>
<label>Enemy Defence + ? </label>
</td>
<td>
<input placeholder="e.g: 6" id="enemydef+">
</td>
</tr>
<tr>
<td>
<button id="calculate">
Calculate
</button>
</td>
<td>
<div id="result"></div>
</td>
</tr>
</table>
$(document).ready(function() {
$('#calculate').on('click', function() {
var abase = $('#abase').val();
var abaseEq = $('#abaseeq').val();
var abaseEqLength = abaseEq.length;
abaseEqLength -= 1;
var weaponlvl = $('#weaponup').val();
var enemydeflvl = $('#enemydefup').val();
var weaponup=parseInt(weaponlvl);
var enemydefup=parseInt(enemydeflvl);
var updifference = weaponup - enemydefup;
var plusdifference = [0, '10%', '15%', '22%', '32%', '43%', '54%', '65%', '90%', '120%', '200%'];
var negdifference = {};
var result;
var aeqmin=0;
var aeqmax=0;
var lowestdamage="";
var maxdamage="";
var negindex;
var negindexplus = 0;
for (var i = 0; i <= abaseEqLength; i++) {
if (abaseEq[i] == '-') {
negindex = i;
negindexplus += (negindex + 1);
}
}
for (var x = 0; x < negindex; x++) {
lowestdamage = lowestdamage + abaseEq[x];
console.log("Lowest Damage: " + lowestdamage);
}
for (var y = negindexplus; y <= abaseEqLength; y++) {
maxdamage = maxdamage + abaseEq[y];
console.log("Max Damage: " + maxdamage);
}
if (updifference => 0 && updifference <= 10) {
updifference = plusdifference[updifference];
console.log("updifference: "+updifference);
result = "pos";
}
if (updifference < 0 && updifference >= -10) {
var negarray = negdifference * -1;
negdifference[updifference] = plusdifference[negarray];
}
var mindamage = parseInt(lowestdamage);
var maxidamage = parseInt(maxdamage);
if (result == "pos") {
aeqmin = mindamage * (1 + plusdifference[updifference]);
aeqmax = maxidamage * (1 + plusdifference[updifference]);
}
if (aeqmax > 0) {
$('#result').html = aeqmin + "~" + aeqmax;
}
}); // calculate on click function
}); // document ready
the cells of the table get for a short moment a red color . the cells are selected by random numbers.
when a cell has a red color then the user shall click the cell.
if he clicks the cell when the cell is still red then he get a point.
that is the idea. but it not works. when i click the cell nothing happens.
<!DOCTYPE html>
<html>
<head>
<style>
td{font-size:40px; padding:4px 10px;}
</style>
<script>
var blinkColors = new Array('red' );
var zw= new Array();
var blinkColor = 0;
var iterator = 0;
var hit=0;
for (var i = 0 ;i<10;i++){
zw[i]=Math.floor((Math.random() *8) + 1);
}
var myBlink = setInterval(function() {
doBlink();
}, 400);
function doBlink() {
var blinkCell = document.getElementById('blinker' +zw[iterator] );
blinkCell.style.backgroundColor = blinkColors[blinkColor];
blinkColor++;
if (blinkColor == blinkColors.length+1) {
blinkColor = 0;
blinkCell.style.backgroundColor = "transparent";
iterator++;
if (iterator == zw.length) {
alert("You hit. " + hit);
clearInterval(myBlink);
} else {
doBlink(zw[iterator]);
}
}
function hitColor(blink){
if (document.getElementById('blink').style.backgroundColor=="red")
hit++;
}
</script>
</head>
<body>
<table border="1">
<tr>
<td id="blinker0"onclick="melden(blinker6")> A </td><td id="blinker1"> B </td><td id = "blinker2"> C </td>
</tr>
<tr>
<td id="blinker3"onclick="melden(blinker6")> D </td><td id="blinker4"> E </td><td id = "blinker5"> F </td>
</tr>
<tr>
<td id="blinker6" onclick="melden(blinker6)" > G </td><td id="blinker7"> H </td><td id = "blinker8"> I </td>
</tr>
</table>
<br>
</body>
</html>
Pull the second if block out of the first one:
if (blinkColor == blinkColors.length+1) {
blinkColor = 0;
blinkCell.style.backgroundColor = "transparent";
iterator++;
}
if (iterator == zw.length) {
alert("You hit. " + hit);
clearInterval(myBlink);
} else {
doBlink(zw[iterator]);
}
So here is what I have so far. I am very new to javascript. How do I make these dice roll sequentially inside of the divs? Such as only displaying the next random number only after the first one is displayed.
<html>
<style>
.numdiv{
height: 400px;
width: 200px;
border:solid 1px green;
float: left
}
</style>
<head>
<script>
function rollDice(){
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var number3 = document.getElementById("number3");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var d3 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2 + d3;
number1.innerHTML = d1;
number2.innerHTML = d2;
number3.innerHTML = d3;
status.innerHTML = "You rolled "+diceTotal+".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<div class="numdiv" id="number1">
0</div>
<div class="numdiv" id="number2">
0</div>
<div class="numdiv" id="number3">
0</div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td></tr>
</table>
</body>
</html>
You can use the setTimeout() method to delay execution of a function, so that the dice will be rolled one at a time:
function rollDice(){
var status = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal = 0;
var current;
for (current = 0; current < nums.length; current++) {
nums[current].innerHTML = "?";
}
current = 0;
status.innerHTML = "Rolling...";
function rollNext() {
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
current++;
if (current < nums.length) {
setTimeout(rollNext, 1000);
} else {
status.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
}
setTimeout(rollNext, 1000);
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td>
</tr>
</table>
Notice also that I've removed your separate number1, number2 and number3 variables, instead using a single variable num to refer to the list of all of the .numDiv div elements. That way you can easily change how many dice you want to use without changing the JS at all (you'd just add or remove .numDiv elements).
EDIT: As I was posting the above you clarified that you want the user to press the button for each die, not automatically roll all three with a delay. So I guess, maybe something like the following, keeping a counter and the total in variables declared outside the function:
var statusSpan = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal;
var current = 0;
function rollDice(){
if (current === 0) { // reset display
for (var i = 0; i < nums.length; i++)
nums[i].innerHTML = "?";
diceTotal = 0;
}
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
if (++current < nums.length) {
statusSpan.innerHTML = "Current total: " + diceTotal + ".";
} else {
statusSpan.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
statusSpan.innerHTML += "You Win!!";
}
current = 0;
}
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px; text-align: center }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()">Roll next die</button></td></tr>
<tr>
<td><span id="status">Ready to roll?</span></td>
</tr>
</table>
Create a counter variable starting with one outside of your rollDice function and every time that is clicked then increase the counter by one. Then you need to replace all the number variables with just this:
var number = document.getElementById("number" + counter);
I think you know where to go from here. Let me know if you need more guidance!
Building on your existing logic, if you want to display 1 every time user clicks then an alternate approach....
var totalIter = 0;//global var which is set to increments on each click
var diceTotal = 0;
function rollDice() {
totalIter = totalIter + 1; //increment by 1
//Existing logic from your script
var ele = document.getElementById("number" + totalIter);
var d1 = Math.floor(Math.random() * 6) + 1;
var status = document.getElementById("status");
diceTotal = diceTotal + d1;
ele.innerHTML = d1;
status.innerHTML = "You rolled " + diceTotal + ".";
if (diceTotal == 15) {
status.innerHTML += "You Win!!";
}
}
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.