Sum a calculated <td> value - javascript

I am creating a calculator that converts a different opioids medications to a standard opioid dosage. The calculator converts all medications fine but I cannot get the javaScript sum() function to add it all up when a button is clicked. Please help.
Of note, the "totalMED += total[i]).value;" code inside the for loop breaks the medication calculate function (no value is displayed). I don't know why.
P.S. I realize both calculate() functions are basically the same but I couldn't get the relevant values to loop through a single function. I seem to have problems with loops.
Updated code with comments:
<!DOCTYPE html>
<html>
<head>
<SCRIPT language="javascript" src="date.js"></SCRIPT>
<style type="text/css">
...
</style>
</head>
<body>
<form>
<table>
<tr>
<th>Medications</th>
<th>Daily Dose (mg)</th>
<th>MED</th>
<th>Medications</th>
<th>Daily Dose (mg)</th>
<th>MED</th>
</tr>
<tr>
// ---this input box is really just a label----
<td><input class="tg-yw41" type=”text” name=”Tramadol” value=Tramadol id="med”
disabled></td>
// ----This input box takes user entered dosage, calls calculate() function, and
// passes the conversion factor---
<td>'TEXT"</td><td><input class ="tg-yw41" type=”text” name=”dose” value=""
placeholder="0" Id="r18c2" onchange="calculate28('.1')"></td>
//---This input box receives the value from the calculate function via Id="MED-
// Tramadol". Also includes name="sum" for sum() function.
<td><input Id="MED-Tramadol" type=”text” name="sum" value="" disabled></td>
//----The next three rows are just duplicate of above
<td><input class="tg-yw41" type=”text” name=”Sufentanil” value="Sufentanil"
disabled></td>
<td><input class ="tg-yw41" type=”text” name=”dose” value="" placeholder="0"
Id="r18c5" onchange="calculate29('60')"></td>
<td><input Id="MED-Sufentanil-intra" type=”text” name="sum" value="" disabled></td>
</tr>
<tr>
//-----Label
<td><input value="Total Daily Morphine Equivalent Dose (MED) in Milligrams"
disabled></td>
//---Input box that should receive value from sum() function (via ID="r19c2")
<td><input class ="tg-yw41" type=”text” name=”dose” value="" placeholder="0"
Id="r19c2"></td>
</tr>
//A button that when clicked calls the sum() function
</table>
<button type="button" onclick="sum()">MED total</button>
JavaScript functions
<script type="text/javascript">
//Takes user input * passed conversion factor, assigns value to
document.getElementById('MED-Tramadol')
function calculate28(x)
{
var my1 = x;
var my2 = document.getElementById('r18c2').value;
//Note: value is parsed as a Float...don't know if it gets converted back to string
document.getElementById('MED-Tramadol').value = parseFloat(my1) * parseFloat(my2);
}
//same as above
function calculate29(x)
{
var my1 = x;
var my2 = document.getElementById('r18c5').value;
document.getElementById('MED-Sufentanil-intra').value = parseFloat(my1) * parseFloat(my2);
}
//Supposed to combine all values from calculate() function assigned to respective boxes
function sum() {
//should collect value from all <input> with name="sum"
var total = document.getElementsByName('sum').value;
var sum = 0;
for(var i=0; i<total.length; i++)
{
totalMED += paredFloat(total[i]).value);
}
document.getElementById('r19c2').value = totalMED;

When you pull the value of an input box, it's read as a string. Use parseInt() to get the number, otherwise you're concatenating strings.
Since you're taking in user input, you should also validate it. A simple way to make sure you don't get NaN is to pull the value into a temporary variable and test it before parsing.
var strTemp = total[i].value;
if (strTemp)
{
totalMED += parseInt(test);
}
EDIT: I ignored the paren, thinking it was just a typo in the question. I decided I shouldn't. You'll see small errors like the unmatched ) inside your call easily if you check your browser's JS console, as this would certainly halt the program and provide an error message.

I'm just going to post this answer out here, and if it doesn't help or it's close then we can edit as we see fit.
First of all, are you sure that you are receiving the correct values in each of the variables? For example, var total = document.getElementsByName('sum').value; should return as undefined.
Secondly, totalMED += total[i]).value; is not valid Javascript, and even if var total = document.getElementsByName('sum').value; were to give you an array of actual values.. then totalMED += total[i]).value; would just concatenate strings. For example, if you have 2 input elements on your page, and the first has a value of 20 and the second has a value of 25 then, your output would be 02025, because value is of type string.
I think this may help:
Javascript
function sum()
{
var total = document.getElementsByName('sum');
var totalMED = 0;
for(var i = 0; i < total.length; i++)
{
if(!isNaN(parseInt(total[i].value)))
{
console.log(total[i].value);
totalMED += parseInt(total[i].value);
}
}
console.log(totalMED);
}
Here is a JSFiddle to prove that it's working.
Let me know if this helps.

Related

Total price calculation with Javascript

Am trying to multiply two cells in HTML table. Here below the code I created:
function multiply() {
var u_price = parseFloat(document.getElementsByName("u-price"));
var s_meter = parseFloat(document.getElementsByName("s-meter"));
var t = u_price * s_meter;
document.getElementById("tot-price").value = t.toFixed(3);
}
<tr>
<td><input type="text" class="input-box" name="u-price" value="0" onKeyUp="multiply();"></td>
<td><input type="text" class="input-box" name="s-meter" value="1" onKeyUp="multiply();"></td>
<td><input type="text" class="input-box" name="tot-price" id="tot-price" disabled></td>
</tr>
The value returned is NaN.
Can you please advise on how to handle this.
Thank you in advance!
A couple changes needed:
getElementsByName returns an array of elements matching the name parameter.
So if you're using this method, you should change it to getElementsByName[0] and make sure you only have one element that matches (i.e. - no other elements with a matching name).
You forgot .value
So your function should look like this -
function multiply() {
var u_price = parseFloat(document.getElementsByName("u-price")[0].value);
var s_meter = parseFloat(document.getElementsByName("s-meter")[0].value);
var t = u_price * s_meter;
document.getElementById("tot-price").value = t.toFixed(3);
}
document.getElementsByName returns an array of elements by that name and hence we need to access the value of the first element of that array.
Instead of document.getElementsByName("u-price"),
You will have to use document.getElementsByName("u-price")[0].value to get the value.

Calculate quantity and total on an order form in javascript

I'm looking for some help with a bit of code please. I'm supposed to create a form that allows the user to input a quantity for items which they wish to purchase. When the quantity is input, the total price for that particular item is displayed, and the grand total (at the bottom of the form) for all purchases.
When the user presses the submit button, an alert popup appears.
I'm having trouble with the calculation part in javascript. It is not calculating any of the total amount or quantity values.
(For some reason the code won't indent here properly but they are in the actual documents).
function calc(){
var QtyA = 0; var QtyB = 0; var QtyC = 0;
var TotA = 0; var TotB = 0; var TotC = 0;
var PrcA = 3; var PrcB = 4; var PrcC = 5.50;
if (document.getElementById('QtyA').value > "");{
QtyA = document.getElementById('QtyA').value;}
TotA = eval(QtyA) * eval(PrcA);
TotA = TotA.toFixed(2);
(document.getElementById('TotalA').value = TotA);
if (document.getElementById('QtyB').value > "");{
QtyB = document.getElementById('QtyB')value;}
TotB = eval(QtyB) * eval(PrcB);
TotB = TotB.toFixed(2);
(document.getElementById('TotalB').value = TotB);
if (document.getElementById('QtyC').value > "");{
QtyC = document.getElementById('QtyC')value;}
TotC = eval(QtyC) * eval(PrcC);
TotC = TotC.toFixed(2);
(document.getElementById('TotalC')value = TotC);
Totamt = eval(TotA) + eval(TotB) + eval(TotC);
Totamt = Totamt.toFixed(2); //fix to 2 decimal places
(document.getElementById('Grand Total is: ').value = Totamt);
alert (Totamt);
<html>
<head>
<meta charset="UTF-8">
<title>Order Form</title>
<style>
#import "css/OrderForm.css";
</style>
<body>
<form>
<table border="1">
<tr>
<th>Item</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td width="80">Hat</td>
<td><img src="images/hat.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€3.00</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td width="80">T Shirt</td>
<td><img src="images/t_shirt.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€4.00</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td width="80">Glasses</td>
<td><img src="images/glasses.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€5.50</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td> Total: </td>
<td><input type="text" id="GrandTotal" size="15" onchange="calc()"></td>
</tr>
</table>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
Ok, as a teacher, I just can't let all the bad habits that someone is trying to teach you go. So, here we go....
eval() is EVIL - Don't use it, ever!
eval() tells the JavaScript runtime to process a string as if it were JavaScript. This is very dangerous because if the string contains malicious code, eval() will run it. In your code, you run eval() on the value entered into a text box and since you have no idea what value will be entered, you also have no idea what string eval() will receive. This equates to a huge security hole and is one of the reasons eval() should not be used. Secondly, even in a perfect world, eval() is slow, so from a purely performance standpoint, you wouldn't want to use it. Frankly, I'm shocked that someone taught you to use it and especially for converting strings to numbers. That alone is enough to ask for your money back!
In your case, you need to convert the string input into numbers so that you can do math with the input. JavaScript offers several ways to do this:
parseInt(stringContainingNumber, radix)
parseFloat(stringContainingNumber)
Number(stringContainingNumber)
+stringThatIsNumber Unary Operator
Don't set up your event handling in HTML with event attributes.
When JavaScript was first created (25+ years ago), the way to set up an event handler for an HTML element (a.k.a DOM element) was to use HTML attributes such as onclick, onchange, onmouseover, etc. inline with the element in the HTML. Unfortunately, because of how simple that technique looks it gets used over and over again instead of dying the quick death it deserves. There are several reasons not to use this outdated technique. Today, we have modern standards and best practices to follow and so, event handling should be done in JavaScript, separate from HTML, with .addEventListener()
Also, your code of: onchange "calc()" was incorrect anyway because the code should have been: onchange = "calc()".
Additionally, think about what elements need events set up for them. Your original code had it set up so that if the total gets changed, calc() would run, but that makes no sense. Why would someone be able to change the total directly and what would doing so actually cause to happen? Should the quantity change because the total has changed?
Pay attention to details
You have 3 rows to calculate 3 quantities * 3 prices to get 3 totals, but you just copied/pasted the HTML for the 3 rows and wound up with 3 input elements with the same id of QtyA even though your JavaScript was correctly looking for QtyB and QtyC.
Do your styling with CSS, not HTML
All of your quantity input fields need to have their width set to a size of 5. Don't use the HTML size attribute for that, do it with the width CSS property. The HTML will be cleaner and you won't have to repeat the same instruction 3 times.
#import is being used incorrectly
The CSS #import directive is meant to be used as the first line in external stylesheets that import instructions from another stylesheet, effectively combining multiple sheets into one. If you have only one stylesheet to use, you don't import it, you link to it.
Instead of: <style> #import "css/OrderForm.css";</style>
use: <link href="css/OrderForm.css" rel="stylesheet">
When you are just displaying a result, don't place it into a form field.
There's no reason to put a total into an input field when you don't want the user to be able to modify that result. Instead, just place it as the text of a non-editable element - - in your case the appropriate cell of the table.
Lastly: Use the developer's tools!
All modern browsers incorporate "developer's tools", which you can activate by pressing F12. There are many tabs in the tools, but the "Console" tab is probably the most important for you right now. If you have errors in your syntax (as you did), the Console will show them and the line number. You must eliminate all of your syntax errors before you can expect your code to run.
The Console is also an invaluable tool for testing values in your code. You can insert:
console.log(anything that is supposed to produce a value);
into your code to verify that variables, elements, etc. have the values you think they do.
Now, in reality, I would go about solving this problem in a very different way that you are attempting, but that is more complex than you are ready for at this stage, so I've gone along with your approach somewhat.
Please read through the HTML and JavaScript comments carefully to explain what's being done.
<!DOCTYPE html> <!-- The DOCTYPE tells the browser what version of HTML it should be expecting. -->
<html>
<head>
<meta charset="UTF-8">
<title>Order Form</title>
<!-- To reference a single stylesheet, use the link element: -->
<link href="css/OrderForm.css" rel="stylesheet">
<style>
/* Make all the input elements that have an id that starts with Qty
be 5 characters wide. (Now size=5 isn't needed in the HTML 3 times) */
input[id^=Qty] { width:5em; }
/* The first <td> in each row should be 80px wide. Now we don't have to
clutter up the HTML with this and we don't have to repeat it 3 times. */
td:first-child { width:80px; }
</style>
</head> <!-- You didn't close your <head> tag! -->
<body>
<form>
<table border="1">
<tr>
<th>Item</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>Hat</td>
<td><img src="images/hat.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA"></td>
<td>€3.00</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalA"></td>
</tr>
<tr>
<td>T Shirt</td>
<td><img src="images/t_shirt.jpg" alt="T-Shirt"></td>
<td><input type="text" id="QtyB"></td>
<td>€4.00</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalB"></td>
</tr>
<tr>
<td>Glasses</td>
<td><img src="images/glasses.jpg" alt="Glasses"></td>
<td><input type="text" id="QtyC"></td>
<td>€5.50</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalC"></td>
</tr>
<tr>
<td> Total: </td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<!-- You need to have this cell span over the remaining columns of the
table, so colspan=4 needs to be added. -->
<td id="grandTotal" colspan="4"></td>
</tr>
</table>
<!-- Your form doesn't actually submit data anywhere, so you shouldn't
have a submit button. A regular button will do. -->
<input type="button" value="Get Grand Total">
<input type="reset" value="Reset">
</form>
<script>
// Get references to the HTML elements that you'll be working with
var qtyBoxA = document.getElementById('QtyA');
var qtyBoxB = document.getElementById('QtyB');
var qtyBoxC = document.getElementById('QtyC');
var totBoxA = document.getElementById('TotalA');
var totBoxB = document.getElementById('TotalB');
var totBoxC = document.getElementById('TotalC');
var grandTot = document.getElementById('grandTotal');
var btnGetTot = document.querySelector("input[type=button]");
var btnReset = document.querySelector("input[type=reset]");
// Set up event handling in JavaScript, not HTML.
qtyBoxA.addEventListener("change", calc);
qtyBoxB.addEventListener("change", calc);
qtyBoxC.addEventListener("change", calc);
btnGetTot.addEventListener("click", getGrandTotal);
btnReset.addEventListener("click", reset);
var gt = null; // Will hold the grand total
function calc() {
var priceA = 3;
var priceB = 4;
var priceC = 5.50;
gt = 0;
// Convert the values in the quantity textboxes to numbers. The 10 that
// is being passed as the second argument indicates the "radix" or the
// numeric base system that should be used when the string is being
// interpreted. Here (and often), we work in the base 10 numeral system.
var qtyA = parseInt(qtyBoxA.value, 10);
var qtyB = parseInt(qtyBoxB.value, 10);
var qtyC = parseInt(qtyBoxC.value, 10);
// If each of the quantity fields are not empty, calculate the price * quantity
// for that row, place the answer in that row's total field and add the answer
// to the grand total
// NOTE: You had semicolons like this: if(); {}, which is incorrect.
// NOTE: Notice that there are + signs right in front of the total box references?
// this forces a conversion of the string in the text to a number. Since we
// just put a number into the cell, we know for sure it can be converted.
// NOTE: If parseInt() can't parse a number from the string provided, it returns NaN
// (Not A Number), we can check to see if we got NaN with the isNaN() function
// and here, we want to know if we don't have a NaN, so we prepend a ! to it
// (the logical NOT operator) to test the opposite of the isNaN() function result.
if (!isNaN(qtyA)) { totBoxA.textContent = qtyA * priceA; gt += +totBoxA.textContent; }
if (!isNaN(qtyB)) { totBoxB.textContent = qtyB * priceB; gt += +totBoxB.textContent; }
if (!isNaN(qtyC)) { totBoxC.textContent = qtyC * priceC; gt += +totBoxC.textContent; }
grandTot.textContent = gt.toFixed(2); // Just place the answer in an element as its text
}
function getGrandTotal(){
calc(); // Make sure all values are up to date
alert(gt);
}
function reset(){
// The built-in functionality of the <input type=reset> will clear out
// the quantity input fields automatically, but we need to manually reset
// non form field element that have been modified:
totBoxA.textContent = "";
totBoxB.textContent = "";
totBoxC.textContent = "";
grandTot.textContent = "";
}
</script>
</body>
</html>

Using the current variable when tracking multiple variables with jQuery event

Below you'll find a simplified example of the code I am using and what I am trying to accomplish.
I'm tracking multiple variables with jQuery that need to call a function on a certain event. The problem is that I don't manage to use only that variable that just changed.
In the HTML body section I have a couple of input fields where people can fill in a number. That number should be formatted with commas as a thousand seperator. Thanks to Elias Zamaria I found an good solution for this (https://stackoverflow.com/a/2901298/7327579). Now I want this implemented with jQuery so I can track all of my variables that will get number inputs at once.
<html>
<title></title>
<head>
In the head of the html I insert my script to track my variables:
<script language="javascript">
var Currency = function() {
this.currencyType = $("#businessAuthorisation, #businessIncome, #entityIncome, #entityAuthorisation);
The function that formats the numbers and should only get the current number from the current variable that is being changed:
this.formatCurrency = function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
};
};
Tracking starts and on the keyUp event my function is called. Only the current variable should be a parameter of the called function.
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
currency.formatCurrency(this);
});
});
</script>
</head>
Here below are the concerning input fields in my form:
<body>
<form>
<table>
<tr>
<td><input type="number" name="entityAuthorisation" id="entityAuthorisation" value="<%=entityAuthorisation%>></td>
</tr>
<tr>
<td><input type="number" name="businessAuthorisation" id="businessAuthorisation" value="<%=businessAuthorisation%>"></td>
</tr>
<tr>
<td><input type="number" name="entityIncome" id="entityIncome" value="<%=entityIncome%>"></td>
</tr>
<tr>
<td><input type="number" name="businessIncome" id="businessIncome" value="<%=businessIncome%>"></td>
</tr>
</table>
</form>
</body>
</html>
How can I make sure that that the function only applies to the current element that caused the event?
In a jQuery event handler, this refers to the element that the event was triggered on. And you need to use .value to get the value of an input. So you should write:
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
this.value = currency.formatCurrency(this.value);
});
});

If-expression in JavaScript with HTML (optional) button in one function

I'm creating a HTML table with fields, that have to be filled, but I want to make one of the fields optional. My code is something like this:
name.html
...
<table>
<tr>
<td>A number:</td>
<td><input id="numb1" type="text"/></td>
</tr>
<tr>
<td>Anoder number (optional)</td>
<td><input id="numb2" type="text"></td>
</tr>
</table>
<input type="button" value="Click" onclick="forfun()"/>
<pre id="result">
Result
</pre>
...
In my jaava.js I want to use an if-else expression, defining, that if the optional field is not empty, then the variable should take the value of the number, written in the field.
function forfun() {
var numberOne=document.getElementById("numb1").value;
numberOne =parseFloat(numberOne); // numberOne is now really a number
var numberTwo=document.getElementById("numb2").value;
numberTwo=parseFloat(numberTwo);
...
if(numberTwo==NaN) { //Here comes the problem, I tried also with
//undefined and ==0, but after pressing the button, I become the results
//of my functions in this loop with result NaN
numberTwo=2;
//and so on
...
}
}else {
//After I fill the second field, everything here is ok
}
What should I write between the brackets after if? Would you give me some ideas?
Comparison with NaN always returns false, so even NaN == NaN will return false. Instead use the built-in isNaN() function:
if (isNaN(numberTwo)) {

Pass the value of html input text to Javascript Function and get the result

This is my very first time I'm using Javascript.
I have this Script:
<script type="text/javascript">
function baunilha()
{
var qb=document.getElementById("quantbaunilha").innerHTML;
var prbau=5.58;
var totbau=qtd*prbau;
}
document.getElementById("valorlinhab").innerHTML=baunilha();
</script>
And, this is how the Function is called:
<tr>
<td><img src="/imagens/DOB_Baunilha.PNG" style="vertical-align: middle" alt="Ima_Bau"> </td>
<td>Caixa de 42 Unidoses de Detergente Ultra-Concentrado aroma Baunilha</td>
<td><input id="quantbaunilha" name="quantbaunilha" value="0" maxlength="2" type="text" size="2" onchange="baunilha()"></td>
<td><input id="valorunib" name="valorunib" size="6" value="5.58">€</td>
<td><input id="valorlinhab" name="valorlinhab" size="8" value="0.00">€</td>
</tr>
So, I want that the result of the Function apears in text-box id="valorlinhab".
I tried the examples of w3schools, but they didn't work, as others examples in the web.
Is there someone who could help me? Any help is wellcome.
Thank you, in advance.
You need to be using value instead of innerHTML. Additionally, you are using "qtb" instead of "qb" in your calculation. You should also set the value inside the baunilha function. Finally, you must tie an event listener to the input so that it will call the javascript function.
I also added a line which would check if the input is actually a number.
function baunilha()
{
var qb=document.getElementById("quantbaunilha").value;
//check that quantbaunilha is a number
if(isNaN(parseFloat(qb)))
{
alert('Enter a number');
return;
}
var prbau=5.58;
document.getElementById("valorlinhab").value=qb*prbau;
}
document.getElementById("quantbaunilha").addEventListener('change', baunilha);
Here is a fiddle: http://jsfiddle.net/uLfcG/3/
You use innerHTML to put the results in to an element's inner HTML for a tag with both an opening and closing tag (like <p>).
Also, since you are using it for your onchange event, you should move the value setting in to the function as well.
For <input>, you set the value attribute instead:
<script type="text/javascript">
function baunilha() {
var qb=document.getElementById("quantbaunilha").value;
var prbau=5.58;
var totbau=qb*prbau;
document.getElementById("valorlinhab").value=totbau;
}
</script>
That should do the trick.
Here is a JSFiddle with a working example: http://jsfiddle.net/U7ZZh/
Also, you had a small typo on the line that is var totbau=qtb*prbau should be var totbau=qb*prbau

Categories

Resources