Round value using selection of drop down menu / radio button - javascript

This consists of two problems. The first problem is rounding numbers to a certain decimal point. The second problem is connecting the drop down menu to the right decimal.
First my code:
<style>
span{font-style:italic;}
span{color:green;}
</style>
<script>
function calcul(){
var sales = parseFloat(document.getElementById("sales").value);
var OpExp = parseFloat(document.getElementById("OpExp").value);
var TaxAll = parseFloat(document.getElementById("TaxAll").value);
var Depre = parseFloat(document.getElementById("Depre").value);
var Divid = parseFloat(document.getElementById("Divid").value);
var TaxR = parseFloat(document.getElementById("TaxR").value);
//GP = Gross Profit
var GP = sales - OpExp;
//TaxInc = Taxable Income
var TaxInc = GP + TaxAll;
//NetInc = Net Income
var NetInc = TaxInc - ((TaxR / 100) * TaxInc);
document.getElementById("NetIncome").innerHTML=
TaxInc - ((TaxR / 100) * TaxInc);
//AtRE = Addition to Retained Earnings
document.getElementById("AtRE").innerHTML = NetInc - Divid;
}
</script>
<form action="" id="nothing">
In 2007 the British building firm Balfour Betty plc had sales of
<input type="text" id="sales" maxlength="6" size="6">
million, total operating expenses of
<input type="text" id="OpExp" maxlength="6" size="6">
million, a tax allowance (rebate) of
<input type="text" id="TaxAll" maxlength="6" size="6">
million because of past losses, and
<input type="text" id="Depre" maxlength="6" size="6">
depreciation. <strong>What is the net income of the
firm?</strong><br />
<br />
Balfour Betty plc paid out <input type="text" id="Divid" maxlength="6" size="6"> million
in cash dividends. <strong>What is the addition to retained earnings?</strong><br />
<br />
The tax rate is <input type="text" id="TaxR" maxlength="6" size="6"> %.<br />
<br />
<input type="button" value="Calculate" id="but" onclick="calcul()" /><br />
<br />
</form>
<strong>The Net Income of Balfour Betty plc is </strong><span id="NetIncome">XXX</span>
<strong> million</strong><br />
<br />
<strong>The addition to retained earnings of Balfour Betty plc is </strong><span id="AtRE">
XXX</span><strong> million</strong>
<br />
<br />
The first problem: rounding numbers. The following answer: <span id="NetIncome"> needs to be rounded dynamically. I've tried to add a new variable called RNetInc and add the following equation RNetInc = NetInc.toFixed(4), but it only gave me two decimals, and after a refresh it doesn't even work anymore. What is the best way to round the answer to N decimals?
The second problem is one I don't know if it's possible. What I have in mind is the following:
A dropdown menu
<select>
<option value"1">1 decimal</option>
<option value"2">2 decimals</option>
<option value"3">3 decimals</option>
</select>
So, what I want is that when I click N decimal, the answer will change to N decimal. This is a very complex situation, but one I often need.
Since I only know the (very) basics of Javascript, even using Google I cannot find the answer. Can someone get me on the right track (if it's even possible)? Thanks in advance.

I'd suggest to fix only the final results, toFixed() returns a string.
HTML for select:
<select id="dec">
<option value="1">1 decimal</option>
<option value="2">2 decimals</option>
<option value="3">3 decimals</option>
</select>
In calcul():
var decs = +(document.getElementById('dec').value); // Add this line
document.getElementById("NetIncome").innerHTML = (TaxInc - ((TaxR / 100) * TaxInc)).toFixed(decs);
document.getElementById("AtRE").innerHTML = (NetInc - Divid).toFixed(decs);
A live demo at jsFiddle (updated).
EDIT
Looks like I've partially missunderstood your question. Please check the updated fiddle, now you can also change the amount of decimals at any time by picking a value from select.

Related

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

calculate bmi with javascript

I am currently creating a program that can calculate bmi with javascript. I am not sure why but it is not working properly. I must be missing something but I am not sure what it is. If someone could help me I would really appreciate it. Thank you.
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8" />
<title>Body Mass Index</title>
</head>
<BODY>
<header><img src="bmi.jpeg" width="380" height="132" border="0" alt="bmi"></header>
<video controls="controls"
width="320px" height="260px">
<source src="bmi.mp4"/>
<p>When it comes to weight loss, there's no lack of fad diets promising fast results. But such diets limit your nutritional intake, can be unhealthy, and tend to fail in the long run.</p>
<p>The key to achieving and maintaining a healthy weight isn't about short-term dietary changes. It's about a lifestyle that includes healthy eating, regular physical activity, and balancing the number of calories you consume with the number of calories your body uses.</p>
<p>BMI is a number calculated from a person's weight and height. BMI provides a reliable indicator of body fatness for most people and is used to screen for weight categories that may lead to health problems.</p>
<p>The BMI ranges are based on the relationship between body weight and disease and death.
Overweight and obese individuals are at increased risk for many diseases and health conditions, including the following:</p>
You need a flash player to view this video.
</video>
<ul>
<li>Hypertension</li>
<li>Dyslipidemia (for example, high LDL cholesterol, low HDL cholesterol, or high levels of triglycerides)</li>
<li>Type 2 diabetes</li>
<li>Coronary heart disease</li>
<li>Stroke</li>
<li>Gallbladder disease</li>
<li>Osteoarthritis</li>
<li>Sleep apnea and respiratory problems</li>
<li>Some cancers (endometrial, breast, and colon)</li>
</ul>
<script type="text/javascript">
function CalculateBMI(){
var inch=12;
var ft;
var bmi= Math.write(weight*703)/ (inch height)^2;
if(bmi<=19)
{"Underweight";
}
if else(19<bmi<=25)
{"Desirable";
}
if else(25<bmi<=29)
{"Prone to health risks";
}
if else (29<bmi<=40)
{"obese"
}
else(40<bmi)
{"Extremely Obese"
}
}
</script>
<form name="bmi">
<p> Weight:<p/></td> <td><input type="text" id="weight" name="weight" size="25" />
<p>Height:</p> <input type="text" id="textbox" name="textbox" size="25" /><td><p>Ft.</p><input type="text" id="textbox" name="textbox" size="25" /> <p>In.</p>
<input type="submit" id="Calculate BMI" name="Calculate BMI" value="Calculate BMI" size="25" onclick="CalculateBMI()" />
According to the Panel on
Energy, Obesity, and Body Weigth Standards published by
American Journal of Clinical Nurttrition, your category is:
<input type="text" id="textbox" name="textbox" size="25" />
</form>
</BODY>
</html>
I see a few things that are likely causing your issue. Lets start with this statement:
var bmi= Math.write(weight*703)/(inch height)^2;
You are not defining weight or height (you have to tell it to look in the textbox or send it to the function it does not automatically know you are referring to a textbox). I would expect something like
var weight = document.getElementById('weight').value;
There is no Symbol between height and weight, which is throwing a syntax error, you need to do something with these if they are going to be together (and do realize this is not adding the inches just calculating the feet in inches).
var bmi= (weight*703)/(inch*height)^2;
After that you are using if else - which is not valid in Javascript you would want to say:
else if (19<bmi<=25)
Lastly you are not returning a value nor specifying WHERE the value should go.
var results;
if (bmi<=19)
{
results = "Underweight"
}
document.getElementById('results').value = results;
Try implementing some of these suggestions and see if that gets you on the right track.
Your javascript had several systemic errors
for example 1<a<12 is not valid, it should be written a>1 && a<12
also, your CalculateBMI function had no idea what weight height in inches or height in feet where. You can include JQuery to make this easier but document.getElementById also works. To accomplish this I also gave meaningful names to your form variables.
You were not displaying the resulting string anywhere. Using getElementById you can also find the result element in your html and set its value to the result of the calculation.
If you don't want the page to refresh when you submit you have to set your form to receive a false value onsubmit.
Your math syntax for the bmi was off, I'm assuming it should be (703 * weight ) (height)^2 where height is in inches (after the foot and inch height variables have been combined).
The cleaned up Javascript should look like this. Note that this is probably not the best way to go about solving this problem.
edit: I think your BMI calculation was off as well. If the input weight and height are imperial (ie inch and lbs) then the inches should be multiplied by 0.025 to get meters and lbs should be multiplied by 0.45 to get kgs.
bmi= (weight_e* 0.45) / (((12*heightf_e)+heighti_e) * 0.025)^2;
function CalculateBMI(){
// To avoid erros due to hoisting define all
// of your vars at the top of your function
var ft,
bmi,
heighti_e, // height in inches
heightf_e, // height in feat
weight_e,
bmi_e, // the bmi element
bmi;
// Use getElementById to get a reference for the
// elements you will be using in your function
heighti_e=document.getElementById("heighti");
heightf_e=document.getElementById("heightf");
weight_e=document.getElementById("weight");
bmi_e=document.getElementById("bmi");
// Not all of these parenthesis are necessary but it
// helps to clear up the order of operation and avoid
// silly mistakes in long equations that are not
// broken up into several lines
bmi= (weight_e* 0.45) / (((12*heightf_e)+heighti_e) * 0.025)^2;
// set bmi to a string value
if(bmi<=19)
{
bmi="Underweight";
}
else if(bmi>19 && bmi<=25)
{
bmi="Desirable";
}
else if(bmi>25 && bmi<=29)
{
bmi="Prone to health risks";
}
else if (bmi>29 && bmi<=40)
{
bmi="obese";
}
else(bmi>40)
{
bmi="Extremely Obese";
}
bmi_e.value=bmi; // bmi_a is the reference to the
// element in your form with the
// bmi id
return false; // make sure you return false to prevent
// page reload
}
I have not cleaned up your HTML form, but at least it now works. I have moved the submission action from the button to the form tag. I have also given the height weight and bmi inputs meaningful id names so we can reference them in the CalculateBMI function.
<form action="" name="bmi" onsubmit="return CalculateBMI()">
<p> Weight:<p/></td> <td><input type="text" id="weight" name="weight" size="25" />
<p>Height:</p> <input type="text" id="heightf" name="textbox" size="25" /><td><p>Ft.</p><input type="text" id="heighti" name="textbox" size="25" /> <p>In.</p>
<input type="submit" id="Calculate BMI" name="Calculate BMI" value="Calculate BMI" size="25" />
According to the Panel on
Energy, Obesity, and Body Weigth Standards published by
American Journal of Clinical Nurttrition, your category is:
<input type="text" id="bmi" name="textbox" size="25" />
</form>

Trying to calculate the total price of items taking into account the quantity selected Javascript

this is my first time posting on this site. i have a webpage that outlines one of my products that I intent to sell
here is my dilemma. I have this code that asks the user to press + and - buttons for the quantity of the item that they want. Now what i am trying to work out is if the user presses + or - any number of times I need to be able to to take into account the number of clicks and calculate the total price for the order on a separate line. Im very new to javascript all help is appreciated thanks
<form>
<br> Item Price: $463.50
<br> Please Select Quantity
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
<input type='button' name='add' onclick='javascript: document.getElementById("qty").value++;' value='+'/>
<input type='text' name='qty' id='qty' />
</form>
<form>
<br> Item Price: $<span id='price'>463.50</span>
var unitprice = (document.getElementById('price').innerText || document.getElementById('price').textContent);
var price = parseFloat(unitprice);
var count = parseInt(document.getElementById("qty").value, 10)
var total = price * count;
alert(total); // or do whatever you want
I would separate out the Javascript code into its own <script> element, and do something like:
<form>
<br/> Item Price: $<span id="price">463.50</span>
<br/> Please Select Quantity
<input type="button" name="subtract" id="subtract" value="-"></input>
<input type="button" name="add" id="add" value="+"></input>
<input type="text" name="qty" id="qty" value="0"></input>
<br/> Total
<input type="text" name="total" id="total" value="0"></input>
</form>
The Javascript would look like:
$(function() {
var price = parseFloat($('#price').text());
$('#subtract').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
if ( current > 0 ) {
$qty.val(current-1);
$('#total').val(price*(current-1));
} else {
$('#total').val(0);
}
});
$('#add').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
$qty.val(current+1);
$('#total').val(price*(current+1));
});
});
You can see it in action.
This is all do-able without jQuery, but it makes life a lot easier!
Since you mentioned you're new to this, a word of WARNING: In the real app only use the quantity from the page, and re-calculate out how much to charge them on the back end. It would be very easy for someone to modify either the price or total in the DOM; if you were to use the price or total from the DOM then a malicious user could buy it for any price they wanted! Always assume input is malicious or incorrect.
var value = parseInt(document.getElementById("qty").value, 10)
item_price = item_price * value;
document.getElementById("someid").innertHTML = item_price;

Dynamically Update fields through Input field and dropdown

I'm trying to dynamically update a text field through an input field. This will then be linked to a dropdown selection with values. I also need to show a due date to show 30 days in advance from today's date.
Here is my HTML:
<div>
<label for="payment">Payment:</label>
<input type="text" name="amount" id="amount" onChange="myfunction()"/>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1">Fast</option>
<option value="2">Medium</option>
<option value="3">Slow</option>
</select>
</div>
<br />
<div>
Payment Breakdown: <br /><br />
Payment:
<div name="amount" id="amount"></div>
Freight:
<div name="delivery" id="delivery"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
</div>
I'm struggling with the Javascript part though and fitting it all together.
I've gotten as far as this and now I'm stuck. (Not very far I know)
function myFunction()
{
var amount = document.getElementById("amount");
var delivery = parseInt($(this).find("option:selected").val());
total = amount + delivery
$("#total").html(total);
};
I've looked at examples on Stackoverflow and Google but nothing seems similar to what I'm trying to achieve. Although I know the answer is out there, I'm not sure if I'm asking the right question.
Cheers
I would change it to this. Here I have an updateCost() function which is called when the amount is changed or the delivery is changed. I also added code to handle the due date.
Remove the inline onchange event from the amount:
<input type="text" name="amount" id="amount"/>
Javascript:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = amount + delivery
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
// handle the due date
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30);
var dateStr = todayPlus30.getDate() + "/" + (todayPlus30.getMonth()+1) + "/" + todayPlus30.getFullYear();
$('#date').html(dateStr);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
Your original code has a few problems:
The wrong case on the inline function call
The use of this within the function when this is not actually any of your elements (you didn't pass it as an argument).
The use of amount in the calculation when amount is an input element, not a value.
From a usability point of view, it would only try to update when the amount is changed, I think it would be better to update on both change of the amount and delivery.

Javascript/Ajax/Jquery Dynamically calculate form on change

I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based on the other ones.
Example:
Total Parts (Mysql)
Labor (User)
Misc (User)
Sub Total (Dynamic total of above)
Tax (Dynamic calc of above - sub * 13%)
Total (Sub + Tax)
I have searched around but can not quite find what I am looking for, and my skills are zero in Javascript/Ajax/Jquery so I haven't been able to modify anything to work, although I have tried miserably.
Can someone help me out on this or point me to a script that may suit my needs.
Thanks
Alright sorry, I thought you were looking for some complex code. Here is a simple example of exactly what you're looking for.
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
Obviously this doesn't grab the dynamic value from a database. If you use PHP you can swap this line:
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
for one like this:
<div>Total Parts: <input type="text" id="parts_input" value="<?PHP include('getTotalParts.php'); ?>" readonly="true" /></div>
Where the getTotalParts.php is a file you make to get your database information. It can simply grab the information and do a "echo $totalParts;"
You can just use onblur (activated when a user leaves each of the input fields) to calcuate the fields.
...<input name="labour" id=total onblur="$('#total').val($('#sub').val() + $('#tax').va())">
You haven't provided enough information to comment on the "Total Parts" field.

Categories