Retrieving numeric value from array and adding itself - javascript

I seem to be struggling with getting this "financial tracker" to work. It's supposed to take all of a class's value ($0.00 +) and add it together. The list can grow by creating more '.cost' and add as many items that cost up to $9999. It will then replace the value of "debit".
My problem is that I can't use innerHTML to get/retrieve or replace any values or edit the html directly. I've tried from using .firstChild to .value, converting to global variables. I feel like I'm not understanding "appendChild" enough as I can't figure out how to change innerHTML without using innerHTML in this case.
This is for homework so I'd much rather have a description than just code and nothing to explain so I can progress and learn! I've spent days searching everywhere for this issue and nothing has quite solved it. My code is below:
var purchases = document.querySelector('tbody');
var debit = document.querySelector('.debits');
var credit = document.querySelector('.credits');
var purchCount = 0;
document.querySelector('.frm-transactions').addEventListener('submit', function (evt) {
let div,
checkbox,
label,
labelText,
purchText,
type,
trash;
labelText = evt.target.elements['description'].value;
type = evt.target.elements['type'].value.trim();
amount = evt.target.elements['currency'].value;
purchCount += 1;
if (labelText === '') {
labelText = 'Transaction ' + (purchCount);
}
tr = document.createElement('tr');
td1 = document.createElement('td');
td2 = document.createElement('td');
td3 = document.createElement('td');
td4 = document.createElement('td');
i = document.createElement('i');
label = document.createElement('label');
purchText = document.createTextNode(labelText);
typeText = document.createTextNode(type);
cost = document.createTextNode("$" + amount);
label.setAttribute('for', 'todo-' + purchCount);
tr.appendChild(td1).setAttribute('class', 'weee');
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
td1.appendChild(purchText);
td2.appendChild(typeText);
td2.setAttribute('class', type);
td3.appendChild(cost);
td3.setAttribute('class', 'cost');
td4.appendChild(i).setAttribute('class', 'delete fa fa-trash-o');
tr.appendChild(label);
purchases.appendChild(tr);
if (td2.classList == "debit") {
var totalamount = document.querySelector('input[name="currency"]').value;
var sum = 0;
for (var i = 0; i < totalamount.length; i++) {
sum += totalamount;
}
console.log(totalamount);
debit.firstChild.nodeValue += sum;
console.count(sum);
} else if (td2.classList == "credit") {
console.log(td2);
} else {
console.log('error');
}
evt.target.reset();
evt.preventDefault();
});
Example of the generated HTML:
<section class="wrapper">
<h1>Transaction Tracker</h1>
<form class="frm-transactions">
<fieldset>
<legend>Add Transaction</legend>
<div class="frm-group">
<input class="frm-control" type="text" name="description" size="30" placeholder="description" />
</div>
<div class="frm-group">
<select class="frm-control" name="type">
<option value="">type</option>
<option value="debit">debit</option>
<option value="credit">credit</option>
</select>
</div>
<div class="frm-group">
<i class="edit fa fa-dollar"></i>
<input class="frm-control" type="number" name="currency" min="0" max="9999" step="0.01" size="4" placeholder="0.00" />
</div>
<div class="frm-group">
<input class="frm-control" type="submit" value="add" />
</div>
<div class="error"></div>
</fieldset>
</form>
<h2>Transactions</h2>
<table class="transactions">
<thead>
<tr>
<td colspan="4" class="right">
Total debits: <span class="total debits">$0.00</span>
Total credits: <span class="total credits">$0.00</span>
</td>
</tr>
<tr>
<th>Description</th>
<th>Type</th>
<th class="amount">Amount</th>
<th class="tools">Tools</th>
</tr>
</thead>
</table>
</section>
Update, I'm now trying to figure out why the outcome of sum is showing in decimal places/duplicating itself.

Do you have to construct the DOM with JS?
The only way to get the value of a DOM element without innerHTML() is by using element.value. This means the value="some number" on the element itself must be set.
If you have to use your code to generate the HTML, adding a sample of what that HTML looks like would be nice so it is easier to reference instead of parsing it from your code.
As a side note, variable names like "ttt" are generally frowned upon.
Try to stick to normal human readable names that follow this structure: myVariableDoesThings.
EDIT: For your sum issue:
sum += totalamount; is incorrect. You are adding all of the elements to sum with that code.
If you change up your loop to the following it should work (was not sure how to post this without the example, you were also incorrectly adding a .value to your query selector):
var totalamount = document.querySelector('input[name="currency"]');
var sum = 0;
totalamount.forEach(element => sum += element.value);
forEach is like your for loop, but it passes the current item being iterated over into a lambda expression. To keep the for loop, you use totalAmount[i].value to access the current item in the iteration.

Related

Creating a timetable using JavaScript

I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code:
var p = document.getElementById('paragraph');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (let i = 0; i < lines; i++){
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++){
let td = document.createElement('td');
}
tbody.appendChild(tr);
}
p.appendChild(table);
However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table.
Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells?
I think you need something like this to insert the data.
We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function.
<!DOCTYPE html>
<html>
<body>
<div class="inputs">
<input type="text" id="input1" placeholder="Enter first col data" >
<input type="text" id="input2" placeholder="Enter second col data" >
</div>
<br> <br> <br>
<table id="myTable">
<thead style="background-color: beige;">
<tr>
<td>default head row cell 1</td>
<td>default head row cell 2</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button type="button" onclick="myFunction()">add data to body row</button>
<script>
function myFunction() {
var table = document.querySelector("#myTable tbody");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
const val1 = document.getElementById('input1').value;
const val2 = document.getElementById('input2').value;
cell1.innerHTML = val1;
cell2.innerHTML = val2;
}
</script>
</body>
</html>
I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event
In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which information that users entered will be stored. This you can also do by using build in function «insertCell()»
Next, you access the fields in which the user has entered data
Retrieve values ​​using the «value» built-in function
Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step
You can look at the written code below for better assimilation of information
<!DOCTYPE html>
<html>
<body>
<div class="inputs" >
<input type="text" id="firstColumn" placeholder="Enter data here" >
<input type="text" id="SecondColumn" placeholder="Enter data here" >
</div>
<table id="Table">
<thead>
<tr>
<td style="background-color: pink;">Name of first column</td>
<hr>
<td style="background-color: purple;">Name of second column</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button style="background-color: yellow;" type="button" id = "btn">Add</button>
<script>
const button = document.querySelector('#btn');
btn.onclick = function() {
var table = document.querySelector("#Table tbody");
var row = table.insertRow();
var Fcell = row.insertCell(0);
var Scell = row.insertCell(1);
const Fdata = document.getElementById('firstColumn').value;
const Sdata = document.getElementById('SecondColumn').value;
Fcell.innerHTML = Fdata;
Scell.innerHTML = Sdata;
}
</script>
</body>
</html>

Find the sum of a column in html table using Jquery or JS

I have a html table created using jQuery:
success: function(data, textStatus, errorThrown) {
var rows ="";
function formatItem(data) {
return '<td>'+data.name + '</td> <td> ' + data.price + ' </td><td>' + "<input></input>" +'</td>';
}
$.each(data, function (key, item) {
$('<tr>', { html: formatItem(item) }).appendTo($("#foodnames"));
});
}
This is what the interface looks like:
The table is working fine with all the data showing.
The problem is finding the sum of the third column. Where I can enter a number and display it using an id.
Is there anyway to do it?
What you want to do is to use jQuery to select the table, and all of the third td's for each row, then sum it. The basic pseudocode is:
Clear the output box.
ForEach TR
Select the third TD
Add that value to the output box.
End ForEach
To do that in jQuery, you just need to know how to select the right values. Assigning relevant class/id names is helpful.
I put together a basic example that you can run. It will tabulate the total of the third column dynamically, as you change the value. I hard coded the price column, but you could easily put some other values or input there.
I put it in an onChange event handler, but if you are loading the data from a server or something, you could do document onLoad or whenever your ajax is complete.
//trigger an event when the input receives a change
$("#exampleTableContainer table td input").off("change").on("change", function(ele) {
//clear the out put box
$("#totalOut").val("0");
//for the table container, select all tr's within the table's tbody.
//Excluding tbody will also select the thead.
$("#exampleTableContainer table tbody tr").each(function(index, rowElement) {
//tablulate the cost of the current row
var rowCost = parseInt($(rowElement).find(".cost").text()) * parseInt($(rowElement).find(".amount input").val());
//if the rowCost is a valid number, add it to whatever is in the output box
if (rowCost) $("#totalOut").val(parseInt($("#totalOut").val()) + rowCost)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exampleTableContainer">
<table>
<thead>
<tr>
<th class="item">Item</th>
<th class="cost">Cost</th>
<th class="amount">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td class="item">Item 1</td>
<td class="cost">123</td>
<td class="amount">
<input type="number">
</td>
</tr>
<tr>
<td class="item">Item 2</td>
<td class="cost">1</td>
<td class="amount">
<input type="number">
</td>
</tr>
<tr>
<td class="item">Item 3</td>
<td class="cost">2</td>
<td class="amount">
<input type="number">
</td>
</tr>
<tr>
<td class="item">Item 4</td>
<td class="cost">4</td>
<td class="amount">
<input type="number">
</td>
</tr>
</tbody>
</table>
<br>
<div>
Total:
<input id="totalOut" readonly value="0">
</div>
</div>
I'm not sure if you plan to use this in a production environment or not, so maybe this is overkill for what you're trying to accomplish, but I would recommend using an underlying data model bound to the table. Then you can get your sum from your data:
const data = [
{food: "Veggie burger", price: 200, qty:1},
// ...Add as many food items as you like
]
You would be able to use the data to build your table:
// Get a reference to the table and create a document fragment
const table = document.getElementById("table-body");
const body = document.createDocumentFragment();
// Fill the fragment with your data:
data.map((value, key) => {
// Row-building logic goes here
// this probably isn't what you actually do here:
const row = document.createElement("tr");
row.className = key;
for (let x in value) {
const dataCell = document.createElement("td");
dataCell.className = x;
dataCell.innerHTML = value[x];
row.appendChild(dataCell);
}
body.appendChild(row);
});
table.innerHTML = "";
table.appendChild(body);
Then you can calculate your sum based on the data, not the UI:
const subTotal = data
.map((value) => value.price * value.qty)
.reduce((a, b) => a + b);
document.getElementById("total").textContent = subTotal;
You would set an event listener on the table(parent node) and use event.target to find the row and column (.qty in this case) and update the corresponding field (qty) in the data object when the input is changed.
$("#my-table").on("input", (e) => {
// You would probably be better off using a custom attribute than a class since there can be multiple classes, but we'll use class to keep it simple:
const column = $(e.target).parent("td").attr("class");
const row = $(e.target).parent("td").parent('tr').attr("class");
data[row][column] = e.target.value;
console.log(data);
});
This pattern also makes it easy to send the updated data back to the REST API to update your database later.
https://jsfiddle.net/79et1gkc/
I know you said you're using jQuery, but ES6 is much nicer in my opinion.
Try this:
$(document).ready(function(){
var total = 0;
$("#submit").click(function(){
$(".user_input").each(function(){
var value = parseInt($(this).val());
total += value;
});
$("#output").text(total);
});
});
HTML
<input type="text" name="value1" class="user_input"/>
<input type="text" name="value2" class="user_input"/>
<input type="text" name="value3" class="user_input"/>
<button name="submit" id="submit" value="calculate">
Calculate
</button>
<div>
<span>Total:</span><div id="output">
</div>

Adding the values in multiple textboxes to a single textbox in php

I've a form which contains a div inside which contains a two textboxes one for service type and another for amount and an add more button. When i click on add more button. The div will get duplicated per onclick. Now I want the values in each amount textbox to be summed up and should be shown in another textbox total. I've created a JS function to show the value entered in amount textbox on onkeyup. But I didn't got any answer.
Here is the code what I've tried so far..
HTML
<table>
<tr id="service">
<td>
<span>Service Type:</span>
</td>
<td>
<input type="text" name="servicetype" id="servicetype" />
</td>
<td>
<span>Amount:</span>
</td>
<td>
<input type="text" name="amount" id="amount" onkeyup="onkeyupsum()"/>
</td>
</tr>
<tr>
<td>
<input type="button" id="addmore" onclick="duplicate()" value="Add More"/>
</td>
</tr>
<tr>
<td><h4 style="text-align:left; padding:0,300px,300px,0;">Total Amount</h4></td>
<td><input type="text" name="tamt" id="tamt"></td>
</tr>
</table>
Javascript:
<script>
var i = 0;
function duplicate()
{ // function to clone a div
var original = document.getElementById('service');
var rows = original.parentNode.rows;
var i = rows.length - 1;
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
}
function onkeyupsum()
{ // calculate sum and show in textbox
var sum = 0;
var amount1= document.getElementById('amount').value;
sum += parseFloat(amount1);
document.submitform.tamt.setAttribute("value",sum );
}
</script>
Can anyone tell me the way to take the textbox values even from duplicated div to textbox.
What you should do is to give inputs common class name and then in onkeyupsum select all inputs and calculate sum in loop:
function onkeyupsum() { // calculate sum and show in textbox
var sum = 0,
amount = document.querySelectorAll('.amount'), i;
for (i = 0; i < amount.length; i++) {
sum += parseFloat(amount[i].value || 0);
}
document.submitform.tamt.value = sum;
}
and input will look like:
<input type="text" name="amount" class="amount" onkeyup="onkeyupsum()" />
Demo: http://jsfiddle.net/mf7wqkq2/

total price according to quantity written for multiple items [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
hello i am making a shopping cart system but i am stuck in the calculations of total products with number of quantities i want that a user selects a price from drop down and then on entering the quantity it updates the total instant and same goes for the other items . i made a js fiddle for the structure can anyone help me achieve this via simple javascript ?
http://jsfiddle.net/nVCY4/25/
the drop down structure is like
<select id="TIPR1" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
function CalculateTotal(frm) {
var order_total = 0
// Run through all the form fields
for (var i=0; i < frm.elements.length; ++i) {
// Get the current field
form_field = frm.elements[i]
// Get the field's name
form_name = form_field.name
// Is it a "product" field?
if (form_name.substring(0,4) == "TIQT") {
// If so, extract the price from the name
//item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
var test = "TIPR1,TIPR2";
//test = test + i;
var e = document.getElementById(test);
item_price = e.options[e.selectedIndex].value;
// Get the quantity
item_quantity = parseInt(form_field.value)
// Update the order total
if (item_quantity >= 0) {
order_total += item_quantity * item_price
}
}
}
// Display the total rounded to two decimal places
document.getElementById("order_total").firstChild.data = "$" +
}
I do encourage you to try something yourself, the absolute best way to learn, is by doing.
If you include jQuery or a similar library, it's very easy.
Here's an example: http://jsfiddle.net/nVCY4/26/
var selects = $('select');
var inputs = $('input');
selects.change(calculate);
inputs.keyup(calculate);
function calculate(){
var runningTotal = 0;
selects.each(function(i){
var val = parseInt($(this).val());
var qty = inputs.eq(i).val();
runningTotal += (val*qty);
});
$('#grandtotal').html("Grand-total: "+runningTotal);
}​
Add the logic you want to your onchange event, like this:
<select id="TIPR1" onchange="f()" class="table-select" title="Please select">
Where f is the function you want to invoke when something is selected.
Here is a possible solution.. actually, several possible solutions. I don't know how these fields look in the context of the entire form. So one of the methods I show below may work better for you than another one.
I have updated your HTML code only a tiny bit: I made the IDs on the SELECT elements unique so that they could be called easily from the JS.
In the JS code there are three different ways to call your fields and get the values. ONLY ONE must be allowed to run. The others need to be removed or commented out.
This also goes for the bottom portion where you set the value of the total. You did not provide HTML that shows what the order total looks like. So I provided samples for several different ways.
This code is untested, and provided as a way to show you possible solutions to this issue. There are at least 10 more that I can think of off the top of my head, but these are (I think) the best match for the HTML code sample you have provided.
<div id="content">
<table border="1">
<tr>
<th>Book Cover</th>
<th>Title & Author</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td class="image">
<img alt="Book Cover" src="images/covers/2artfielding.png" />
</td>
<td class="title">
<p class="table"><b>The Art of Fielding</b></p>
<p class="table"><i>by Chad Harbach</i></p>
</td>
<td class="price">
<select id="TIPR1" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
</td>
<td class="quantity">
<input type="text" id="artquantity" value="1" /><br />
</td>
</tr>
<tr>
<td class="image"><img alt="Book Cover" src="images/covers/18thelovers.png" /></td>
<td class="title">
<p class="table"><b>The Lover's Dictionary</b></p>
<p class="table"><i>by David Levithan</i></p>
</td>
<td class="price">
<select id="TIPR2" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
</td>
<td class="quantity">
<input type="text" id="loverquantity" value="1" /><br />
</td>
</tr>
<tr>
<td class="image"><img alt="Book Cover" src="images/covers/11nightcircus.png" /></td>
<td class="title">
<p class="table"><b>The Night Circus</b></p>
<p class="table"><i>by Erin Morgenstern</i></p>
</td>
<td class="price">
<select id="TIPR3" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
</td>
<td class="quantity">
<input type="text" id="nightquantity" value="1" /><br />
</td>
</tr>
</table>
<br />
<p class="totals" id="grandtotal">Grand-total:</p>
</div>
<script type="text/javascript">
function CalculateTotal(frm) {
var order_total = 0.00;
var form_select, form_input;
//*****************************************************************
//Option 1: Call the fields directly
//*****************************************************************
form_select = document.getElementById("TIPR1");
form_input = document.getElementById("artquantity");
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
form_select = document.getElementById("TIPR2");
form_input = document.getElementById("loverquantity");
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
form_select = document.getElementById("TIPR3");
form_input = document.getElementById("nightquantity");
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
//*****************************************************************
//*****************************************************************
//Option 2: Create an array and loop through them
//*****************************************************************
var selectIDs = ["TIPR1", "TIPR2", "TIPR3"];
var inputIDs = ["artquantity", "loverquantity", "nightquantity"];
foreach(var i in selectIDs) {
form_select = document.getElementById(selectIDs[i]);
form_input = document.getElementById(inputIDs[i]);
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
}
//*****************************************************************
//*****************************************************************
//Option 3: Assuming there are the same number of SELECTs as INPUTs
//*****************************************************************
var selects = document.getElementById("content").getElementsByTagName("select");
var inputs = document.getElementById("content").getElementsByTagName("input");
foreach(var i in selects) {
form_select = selects[i];
form_input = inputs[i];
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
}
//*****************************************************************
//*****************************************************************
//Display the total rounded to two decimal places
//*****************************************************************
tot_val = "$" + parseFloat(order_total).toFixed(2);
//I don't know what "order_total" is here since you didn't show it in an example...
// - Here is the code to set it if it's an input
document.getElementById("order_total").value = tot_val;
// - ...if it's a block level element like a DIV or P
document.getElementById("order_total").innerHTML = tot_val;
// - ...or if it's a block level child of the element
document.getElementById("order_total").firstChild.innerHTML = tot_val;
//*****************************************************************
}
</script>

Classic asp : How to put cal function work for records that being retrieved from database

Could you please help why my working wage calculating function doesn't work in this code? (It worked fine before I add "Do while" loop into. )
What I want is first retrieve wage amount from database after that user can input other expense and remunerate right to each generated records. When user got the satisfy outcome, he can save this back into database.
Thank you,
My code are as below:
<%
Do while Not Rs.EOF
if rs.fields.item("if_social_sec") = "True" then
displaytxt = ""
soc_sec_v = soc_sec
else
displaytxt = "none"
soc_sec_v = 0
end if
%>
<table>
<form name="myform2" action="salary_action.asp" method="POST">
<tr bgcolor="#<%=color%>">
<td class="btline" width="25" align="center"><input type="checkbox" name="lb_id" value="<%=lb_id%>" onClick="highlightRow(this,'#FFFFCC','#EFF4FA');"></td>
<td class="btline difcursor" nowrap width="7%"> <%=rs.fields.item("lb_name")%></td>
<td class="btline" nowrap width="10%"><input type="text" name="working_day" id="working_day" value="<%=rs.fields.item("MaxOfdays")%>" size="7" onFocus="startCalc();" onBlur="stopCalc();"></td>
<td class="btline " nowrap width="10%"><input type="text" name="wage" id="wage" value="<%=formatnumber(rs.fields.item("Total"),2)%>" onFocus="startCalc();" onBlur="stopCalc();"></td>
<td class="btline " nowrap width="8%"><input type="text" name="OT" id="OT" size="7" onFocus="startCalc();" onBlur="stopCalc();"><input type="hidden" id="OT_rate" value="<%=rs.fields.item("lbOT")%>" ></td>
<td class="btline " nowrap width="8%" ><input type="text" name="soc_sec" id="soc_sec" size="7" value="<%=soc_sec_v%>" onFocus="startCalc();" onBlur="stopCalc();"></td>
<td class="btline" nowrap style="padding-left: 10px" width="8%" ><input type="text" name="ex_pay" id="ex_pay" size="7" onFocus="startCalc();" onBlur="stopCalc();"></td>
<td class="btline bold" width="10%"><input type="text" name="net_wage" id="net_wage" size="7" disabled></td>
<td class="btline" ><input type="submit"></td>
</tr>
</form>
<%
Rs.movenext
n = n + 1
Loop
End if
Rs.close
set Rs=nothing
Call DBConnClose()
%>
</table>
<script>
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
wage = document.myform2.wage.value;
OT_rate = document.myform2.OT_rate.value;
OT = document.myform2.OT.value;
OT_amt = OT_rate * OT;
soc_sec = document.myform2.soc_sec.value;
ex_pay= document.myform2.ex_pay.value;
net_wage = (wage * 1) + (OT_amt * 1) - (soc_sec * 1) + (ex_pay * 1);
document.myform2.net_wage.value = net_wage.toFixed(2);
}
function stopCalc(){
clearInterval(interval);
}
</script>
The problem is that for every record in the database table, you are creating a separate form and all forms have the same name thus JavaScript can't find the actual form when it's executed.
Assuming you want to keep this behavior (of one form for every record) you first have to give unique name to each form by adding some counter,which you already have:
<form name="myform2_<%=n%>" action="salary_action.asp" method="POST">
By adding the counter n you create unique name to each of the forms.
Next step is changing the way you call the functions, you need to tell the JavaScript function who called it so it can grab the proper form. To do this, change the calls to:
onFocus="startCalc(this);" onBlur="stopCalc(this);"
The this is reserved JavaScript identifier and when passed this way it will be the actual element being focused or blurred.
Final step is modifying the JavaScript itself - you will need multiple intervals now, one for each form, so associative array is the most simple solution, having the form name as the key. Code would look like:
var intervals = {};
function startCalc(sender){
var key = sender.form.name;
intervals[key] = setInterval(function() {
calc(key);
},1);
}
function calc(key){
var oForm = document.forms[key];
wage = oForm.wage.value;
OT_rate = oForm.OT_rate.value;
OT = oForm.OT.value;
OT_amt = OT_rate * OT;
soc_sec = oForm.soc_sec.value;
ex_pay= oForm.ex_pay.value;
net_wage = (wage * 1) + (OT_amt * 1) - (soc_sec * 1) + (ex_pay * 1);
oForm.net_wage.value = net_wage.toFixed(2);
}
function stopCalc(sender){
var key = sender.form.name;
clearInterval(intervals[key]);
}
As you see, the form name is now being extracted from the "sender" element then used to get the actual form instead of the single "myform2" which no longer exists as you have multiple forms.

Categories

Resources