Convert currencies in real time using jQuery and or Javascript - javascript

http://jsfiddle.net/6mMUs/
I want to have live currency rate inputs for Euros, Dollars and Pounds.
<input type="text" id="eurorate" style="margin-bottom:15px;"> Euros <br />
<input type="text" id="dollarrate" style="margin-bottom:15px;"> Dollars <br />
<input type="text" id="poundrate" style="margin-bottom:15px;"> Pounds
What's the proper way of assigning a multiplier to each of these 3 currencies and have them respond to change in ANY of the inputs in real time?
for example, if a dollar is 0.75 euros and it is 0.60 Pounds, when I enter '1' in the dollar field, the other fields should show the correct values when converted to the other currencies.
I tried doing this with setInterval but it is not truly real time, I want to know what's the proper alternative using keyup or something like that.
Any help is appreciated.

Use an onkeyup event on your input fields, and when the event fires you update the other ones.

A simple Method to Covert Currency
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function changeTo(toType){
if(toType=="Pound")
cvrate = 0.86;
else
cvrate = 0.78;
$(".currency_change").each(function (index, element) {
var og_val = $(this).data("og-value");
var cvd_val = (og_val*cvrate).toFixed(2);
return $(this).html(cvd_val);
});
}
</script>
</head>
<body>
<br /><span class="currency_change" data-og-value="1254">1254</span>
<br /><span class="currency_change" data-og-value="145">145</span>
<br /><span class="currency_change" data-og-value="54">54</span>
<br /><span class="currency_change" data-og-value="254">254</span>
<br /><span class="currency_change" data-og-value="147">147</span><br />
<button onClick="changeTo('Pound');">Conver To Pound</button>
<button onClick="changeTo('Euro');">Conver To Euro</button>
</body>
</html>

Related

Multiple calculations and targeted output in javascript

As a learning exercise and to also create a simple, but helpful little tool (for me), I am trying to create a web-based form that will take price and quantity data for multiple items and then produce a "per unit cost" (price divided by item quantity). Based on that info, I then want further calculations to provide a final cost based on the cost totals for several unit costs of those items. I have this simple little tool built in an Excel spreadsheet, but I want it in web format also.
I am into shooting as a hobby and I reload my own ammo. This tool takes the bulk price/quantity for four items; bullets, powder, primers, and brass cases, gives the per unit cost and then will tell me the cost per round of ammo (first iteration is the most expensive as new brass casing costs are included), then subsequent loadings (selectable number) is calculated using only bullet, powder, and primer cost since the brass can be reloaded multiple times.
I have the initial start with the html displaying two lines of user input, first line is: bullet, price, quantity, unit. Second line is Powder, price, quantity, unit. The form input is formatted using css grid.
I have a script that works to do the calculations for the first line for the bullet, but I don't know how to get it to reiterate and then calculate and output the powder data. I've read numerous sites concerning form calculations and most if it went right over my head. Some help with this would be appreciated.
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06+bprice)/bquantity;
return bcost.toPrecision(2);
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
return false;
};
}
}());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<title>Unit Cost Calculator</title>
</head>
<body>
<div class="contain">
<div class="wrapper">
<div class="form">
<h2>Load Cost Calculator</h3>
<form id="unitCost" action="">
<p>
<label for="bullet">Bullet </label>
<input id="bullet" name="bullet" type="text" />
</p>
<p>
<label for="bprice">Price </label>
<input id="bprice" name="bprice" type="number" step="0.01" />
</p>
<p>
<label for="bquantity">Quantity </label>
<input id="bquantity" name="bquantity" type="number" />
</p>
<p>
<label for="bunit">Unit Cost </label>
<input id="bunit" name="bunit" type="number" step="0.01" />
</p>
<p>
<label for="powder">Powder </label>
<input id="powder" name="powder" type="text" />
</p>
<p>
<label for="pprice">Price </label>
<input id="pprice" name="pprice" type="number" step="0.01" />
</p>
<p>
<label for="pquantity">Quantity </label>
<input id="pquantity" name="pquantity" type="number" />
</p>
<p>
<label for="punit">Unit Cost </label>
<input id="punit" name="punit" type="number" step="0.01" />
</p>
<p>
<label for="subm"></label>
<input type="submit" value="Calculate Per Unit Cost" />
</p>
<p>
<label for="rest"></label>
<input type="reset" value="Reset" />
</p>
</form>
</div>
</div>
</div>
Ok, the suggestion by Ayaz does work, sort of. I swear I tried that before and it did not. I even still have the old copy where I tried it, I just went back and it doesn't work, but for some reason editing the current working copy, with the exact same code, it works. Sigh, anyway...I've also figured out the code to get and calculate the powder data and it too works.
The formula for the powder unit cost is different than for bullets. Bullets are sold in quantity counts, 50, 100, etc. Powder is sold by weight, typically in 1lb or 8lb containers. However, for calculating per cartridge loading costs there is a second weight unit used, "grains." There are 7000 grains to 1lb. So, the formula I am trying to use for powder is
(pprice*0.06+pprice)/(pquantity*7000)
The 0.06 is there to add in the cost of sales tax. Quantity is entered by the user in pounds, the formula converts it to grains, or is supposed to. When I use that formula, I get weird results. When I run the script with a powder price of 29.99, quantity of 1, it gives me an output of 32. Something is obviously not calculating correctly.
So, I changed the formula to
(pprice*0.06+pprice)/pquantity
and instead of entering 1 for the quantity, I can put in the total grains instead of pounds (7000 for 1lb of powder or 56000 for 8lbs), which is fine since it will always be one or the other.
I then ran into an issue of result precision. The output was only to 4 decimal places on the powder. I needed that output to go to out as far as possible. Since a single grain of powder is incredibly small in terms of price, it seems immaterial, but will be important later when calculating per cartridge prices and especially when calculating multiples of cartridges, such as 20 rounds per "box." The same is true for primers as they come in boxes of 1000. I then tried adding:
return pcost.toPrecision(8);
but that did not change anything. So after adding more fields for primers and brass and playing around, I found that the code line
return bcost,toPrecision(2);
was the culprit. By removing the ".toPrecision" portion, everything returns out to however many decimals it actually calculates to.
On to the next step, now to have it do more math and output the cost of a single, complete round by adding the unit cost for each item together (and then round it up to 2 decimals). Going to go try working on that now...I'll probably have more questions on this..
Here's the current working code:
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06+bprice)/bquantity;
pprice = parseFloat(pprice);
pquantity = parseFloat(pquantity);
pcost = (pprice*0.06+pprice)/pquantity;
prprice = parseFloat(prprice);
prquantity = parseFloat(prquantity);
prcost = (prprice*0.06+prprice)/prquantity;
brprice = parseFloat(brprice);
brquantity = parseFloat(brquantity);
brcost = (brprice*0.06+brprice)/brquantity;
return bcost;
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
this.punit.value = calculateUnitCost(this.pprice.value, this.pquantity.value);
this.prunit.value = calculateUnitCost(this.prprice.value, this.prquantity.value);
this.brunit.value = calculateUnitCost(this.brprice.value, this.brquantity.value);
return false;
};
}
}());
Use the below code if Per Unit calculation formula is same for Powder.
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06+bprice)/bquantity;
return bcost.toPrecision(2);
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
this.punit.value = calculateUnitCost(this.pprice.value, this.pquantity.value);
return false;
};
}
}());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<title>Unit Cost Calculator</title>
</head>
<body>
<div class="contain">
<div class="wrapper">
<div class="form">
<h2>Load Cost Calculator</h3>
<form id="unitCost" action="">
<p>
<label for="bullet">Bullet </label>
<input id="bullet" name="bullet" type="text" />
</p>
<p>
<label for="bprice">Price </label>
<input id="bprice" name="bprice" type="number" step="0.01" />
</p>
<p>
<label for="bquantity">Quantity </label>
<input id="bquantity" name="bquantity" type="number" />
</p>
<p>
<label for="bunit">Unit Cost </label>
<input id="bunit" name="bunit" type="number" step="0.01" />
</p>
<p>
<label for="powder">Powder </label>
<input id="powder" name="powder" type="text" />
</p>
<p>
<label for="pprice">Price </label>
<input id="pprice" name="pprice" type="number" step="0.01" />
</p>
<p>
<label for="pquantity">Quantity </label>
<input id="pquantity" name="pquantity" type="number" />
</p>
<p>
<label for="punit">Unit Cost </label>
<input id="punit" name="punit" type="number" step="0.01" />
</p>
<p>
<label for="subm"></label>
<input type="submit" value="Calculate Per Unit Cost" />
</p>
<p>
<label for="rest"></label>
<input type="reset" value="Reset" />
</p>
</form>
</div>
</div>
</div>

Javascript Issue - HTML division Calculator

I'm in the learning phase the code works fine no issues, however I need to add the below features.
When clicking the mouse on the calculate button it does the calculation and spits the results out correct, however my question is I'd want to use the physical keyboard "enter key" to execute/press the calculate button.
Also I need the form to reset after 5 seconds automatically, how can I do that ?
.
<script Language="Javascript">function Calc(myform){var enternumber1=document.myform.number1.value;var enternumber1=parseFloat(enternumber1,10);if(isNaN(enternumber1)||(enternumber1<0)){alert(" Enter a valid number! ");document.myform.number1.value="";document.myform.number1.focus();}else{var enternumber2=document.myform.number2.value;var enternumber2=parseFloat(enternumber2,10);if(isNaN(enternumber2)||(enternumber2<0)){alert(" Enter a valid number! ");document.myform.number2.value="";document.myform.number2.focus();}else
document.myform.number3.value=enternumber1/enternumber2;}}</script>
<form name="myform">
<br />
<b>Enter your first number:</b> <input maxlength="" name="number1" size=" " type="text" /><br />
<br />
<b>Enter your second number:</b> <input maxlength="" name="number2" size="" type="text" /><br />
<br />
<input name="button" onclick="Calc(myform)" type="button" value="Calculate" /> <input name="Reset" type="Reset" /><br />
<br />
<b>The result is :</b> <input maxlength="" name="number3" size="" type="text" value="" /> </form>
Please try to be clear in whatever you are asking. Lets move to your query now:
From your query I can understand that you are facing issues in doing 2 things:
Calling your Calc('myform') function when Enter key is pressed in second input field. - I am not covering validation of form(should have validation function,to be called before calling Calc() function). Just add an id to both the form tag as well as the second input field.Let say you add myForm and num2 ids in form and second input field respectively.
Once added you can use following function:
<script type="text/javascript">
document.getElementById('num2').onkeypress = function (event) {
if (event.keyCode == 13) {
Calc(myform);
}
};
</script>
**Note:**In this function we are checking every key which is getting pressed when our cursor is in num2 field, if the key pressed is having code 13,which is the keycode of enter key, I am just calling the same function Calc() which you are already using.So it will do the same what its doing on click of Calculate button.
For resetting your form in every 5 seconds.Please add this function:
function resetForm() {
document.getElementById("myForm").reset()
}
setInterval(resetForm, 5000);
Note: We are calling setInterval function here to reset your form in every 5seconds.Please dont forget to add myForm id in your form.

Update Time Element with Javascript

I am using this code to display two fields. One is type=time and the other is type=text.
Using the button and javascript code I am trying to update the values in the fields.
It works perfectly for the text field, but I can't for the life of me get it to work on the time field.
<html>
<body>
<input type="button" name="now" value="in" onclick="settime();" />
<input type="time" step=1 size=10 id="timein" name="timein">
<br /><br />
<input type="button" name="now" value="in" onclick="settext();" />
<input type="text" size=10 id="timetext" name="timetext">
<script>
function settime(){
document.getElementById("timein").value = "10:13:43 AM";
}
function settext(){
document.getElementById("timetext").value = "10:13:43 AM";
}
</script>
</body>
</html>
Can anyone please point out my mistake?
Thanks in advance!
You can not set the AM/PM part of the time. Instead use the 24 hour format to specify that.
function settime(){
document.getElementById("timein").value = "10:13:43";
console.log(document.getElementById("timein"))
}
Check out how the Input Time Value works here: http://www.w3schools.com/jsref/prop_input_time_value.asp

DOM/Javascript not returning a value, results yield NAN. Can't find the error?

I have a logic error and cant seem to find it. I think I am "getting" the elements by ID correctly, but it yields NAN. Any help with this is appreciated.
I am not sure what else I am doing wrong, any suggestions are welcome. I am new to DOM and not very familiar with Javascript.
var avgGrade
function calcAvg()
{
avgGrade = document.getElementById("finalExam") +
document.getElementById("homework") + document.getElementById("projects");
alert("Your average is " + avgGrade);
document.getElementById("stuAverage").value = avgGrade;
}
//-->
</script>
</head>
<body>
<h1>Calculate average</h1>
<h3>Enter the following information and then press the <b>AVERAGE</b> button
to calculate
your grade.</h3>
<p>To clear the data fields, click here <b>Refresh this page</b></p>
<form action="#" name="gradeInfo" id="gradeInfo">
<p>
Enter Final Exam Grade:
<input type="text" name="finalExam" id="finalExam" size="4" /><br />
Enter Homework Grade:
<input type="text" name="homework" id="homework" size="4" /><br />
Enter Projects Grade:
<input type="text" name="projects" id="projects" size="4" /><br />
<br /><br />
<input type="button" value="AVERAGE" onclick="calcAvg()" />
<br /><br />
Your Average is:
<input type="text" name="stuAverage" id="stuAverage" size="4" /><br />
</p>
</form>
</body>
</html>
First missing a ; at the end of var avgGrade
Second you need to get values of the inputs not the inputs itself.
document.getElementById("homework").value
Third you need to convert the values from string to integer using parseInt
avgGrade = parseInt(document.getElementById("finalExam").value) +
parseInt(document.getElementById("homework").value) +
parseInt(document.getElementById("projects").value);
jsfiddle DEMO
P.s. you gotta divide it to the number of grades to get the average.
to get the value in the input field you need to write -
document.getElementById("finalExam").value

Javascript equation with negative and positive numbers

I have four text input fields, after the user enters relevant values, I have to make a JavaScript calculation to add all of them
I use:
var total = Number(value1) + Number(value2) + Number(value3) + Number(value4);
then I display the total:
document.getElementById("value5").innerHTML = total;
If one of the values is negative, it gets added as a positive number. How do I get the equation to treat it as a negative one (so it gets subtracted)?
I dont know what the problem is but it works well
<script type="text/javascript">
function fnc(){
val1=Number(document.getElementById("t1").value);
val2=Number(document.getElementById("t2").value);
var total = val1+val2;
document.getElementById("t3").value=total;
}
</script>
input1: <input type="text" id="t1" />
input2: <input type="text" id="t2" />
<br />
<input type="text" id="t3" />
<input type="button" id="btn" onclick="fnc()" value="click me" />

Categories

Resources