Total price calculation with Javascript - 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.

Related

Auto Calculate with already given value

I want to get fee value with already calculated value without using onblur function.
HTML and JS Snippet:
var initialcost = document.getElementById("initialcost");
var Tfee = initialcost - (initialcost * 5)/100;
document.getElementById("fee").value = +Tfee;
<input type="text" readonly="readonly" value="1000" id="initialcost">
<input type="text" readonly="readonly" id="fee">
After autocalculating read-only value from id="initialcost" display the value in id="fee"
After trying this I get no result
Kindly help
You're attempting to calculate things using the element, not its value.
Replace
var initialcost = document.getElementById("initialcost");
with
var initialcost = parseFloat(document.getElementById("initialcost").value);
Example with automatic recalculation to boot:
var initialCostElement = document.getElementById("initialcost");
function compute() {
var initialcost = parseFloat(initialCostElement.value);
var Tfee = initialcost - (initialcost * 5)/100;
document.getElementById("fee").value = +Tfee;
}
initialCostElement.addEventListener("input", compute, false);
compute();
<input type="number" value="1000" id="initialcost">
<input type="text" readonly="readonly" id="fee">
first of all,
you are using the html element itself instead of its value in your calculation.
use:
var initialcost = document.getElementById("initialcost").value;
Moreover, I would replace the "var" type with contest in both variables since this are constants with non-changing values. The var is a more "old-fashioned" approach since "let" and "const" are newer additions to the js syntax,
Good luck!

Sum a calculated <td> value

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.

Javascript to populate phone number into 3 input textboxes with indentical names no id

I essentially have some weird voodoo stuff I have to fix.
This old classic asp code for generating textboxes looks like this
<%i3_addPhoneFields "requestorPhone1","Phone <font class =txtMedium>:<font color = red>*</font></font>",i3_EmpPhoneNumber%>
I see that the OUTPUT view source is
<input class="txtSmall" type="text" name="requestorPhone1" value="" size="3" maxlength="3">
<input class="txtSmall" type="text" name="requestorPhone1" value="" size="3" maxlength="3">
<input class="txtSmall" type="text" name="requestorPhone1" value="" size="4" maxlength="4">
I didn't know the name repeated 3 times is valid html
I cannot just add in ID's for each one
I cannot just go changing all this code for several reasons.
I have javascript variables for phone number like this:
(888) 433-3017
What I have is essentially added in Jquery
If I do this then ALL 3 text boxes will essentially get the same value (222 - obviously)
$('input[name="requestorPhone1"]').val('222');
GOAL
To use javascript / jquery with regex and to take
(888) 433-3017
For 1st textbox to put in 888 , 2nd textbox 433 , 3rd textbox 3017
Here's one approach for splitting the number and then populating it into textboxes:
function doIt() {
var myString = "(123) 456-7890"; //hard-coded number for demo
myString = myString.replace(/\D/g,''); //remove all non-numerics
console.log(myString);
//extract component parts from the full number string
var first = myString.substr(0,3); //extract the first part of number
var second = myString.substr(3,3); //second part
var third = myString.substr(6,4); //third part
console.log(first, second, third);
//use jQuery's eq() to select specific elements in order
$('input[name="requestorPhone1"]:eq(0)').val(first);
$('input[name="requestorPhone1"]:eq(1)').val(second);
$('input[name="requestorPhone1"]:eq(2)').val(third);
}
There's JSFiddle demo here: http://jsfiddle.net/hh2o1bek/
Obviously I've hard-coded the number, but this should be enough to point you in the right direction.
You could something like this:
var els = document.getElementsByClassName("txtSmall");
if (els[0])
els[0].value = "888";
if (els[1])
els[1].value = "433";
if (els[2])
els[2].value = "3017";
JS + Jquery :
str = '(888) 433-3017';
a = str.split(' ');
a[0] = a[0].replace(/[^0-9]/g, '');
b = a[1].split('-');
$('input[name="requestorPhone1"]').eq(0).val(a[0]);
$('input[name="requestorPhone1"]').eq(1).val(b[0]);
$('input[name="requestorPhone1"]').eq(2).val(b[1]);
https://jsfiddle.net/y9w8nwop/2/

Jquery child>Parent>child>child selector

I need help with my following code:
Html:
<table>
<tr class="oc">
<td class="process">process</td>
<td><input name="data" /></td>
</tr>
<tr class="oc">
<td class="process">process</td>
<td><input name="data" /></td>
</tr>
</table>
On click of td[class=process] , I need the value of input[name=data]. I tried in several ways and failed. I attempts include follows:
Inside Jquery on click function:
var v = $(this).parent().children(":eq(2)").children().val()*1;
var v = $(this).parent().children.children("input[name=data]").val()*1;
var v = $(this).parent().find("input[name=data]").val()*1;
var v = $(this).parent().children(":eq(2)").children().val()*1;
What happening is, every time I click the td[class=process], I am getting the previous value of input[name=data] + current value of input[name=data]
And, I have no idea why. Help would be highly appreciated.
Your third variant already works.
var v = $(this).parent().find("input[name=data]").val()*1;
Your 2nd approach is incorrect, as children is a function.
Your 1st and 4th approach (unless I'm blind) are the same. However, since :eq() is zero-indexed; the <td> you're selecting is actually position 1, not 2. You can see this working here.
var v = $(this).parent().children(":eq(1)").children().val()*1;
You may also like to hear about next(), which might make this a bit easier.
var v = $(this).next().children().val() * 1;
See next(), and this fiddle.
using jquery it is very simple
$('.process').click(function(e)
{
var myData = $(this).next().children().val();
});
You can use next() to target the next column and then find() or children() to access the input inside it.
$("td.process").click(function(){
var v = $(this).next("td").find("input[name='data']").val();
})
$(this).next().find('input[name=data]').val()

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