percentages when converting sterling to euro - javascript

Hi I am trying to convert Sterling to Euros. But I can't seem to get the percentages correct. I have tried it several ways without luck. The idea is to get 1% of the sterling price then multiply it by the conversion rate and add it to the sterling price to make the euro total, and then do the same with vat.
Hope someone can help, thanks!
Here is my code.
var input = document.querySelectorAll('input');
var conversionRate = input[0];
var sterling = input[1];
var vat = input[2];
var euro = input[3];
init();
function init() {
calculateKeyUp();
}
function calculateKeyUp() {
for (var i = 0; i < input.length; i++) {
input[i].addEventListener("keyup", function() {
//var totalLessVat = (sterling.value) + (conversionRate.value * (sterling.value / 100));
var sterling1Per = sterling.value / 100;
var convert = sterling1Per * conversionRate.value;
var totalLessVat = convert + sterling.value;
//var total = (totalLessVat) + (vat.value * (totalLessVat / 100));
var euro1Per = totalLessVat / 100;
var addVat = euro1Per * vat.value;
var total = addVat + totalLessVat;
euro.value = Math.floor(total);
});
}
}
<div id="calculator-form">
<table>
<tr>
<td>Conversion Rate: </td>
<td><input type="number" id="conversionRate"> %</td>
</tr>
<tr>
<td>Sterling Price: </td>
<td><input type="number" id="sterling"> £</td>
</tr>
<tr>
<td>Vat: </td>
<td><input type="number" id="vat"> %</td>
</tr>
<tr>
<td>Euro Price is </td>
<td><input type="number" id="euro" disabled> €</td>
</tr>
</table>
</div>

The .value of an input is going to be a String, so you will need to parse the number out of each input you are working with. If it's an int you can use:
var sterling1Per = parseInt(sterling.value, 10) / 100;
If it's a float, you can use:
var sterling1Per = parseFloat(sterling.value) / 100;
Anywhere that you use an input .value that needs to be a number needs to be parsed accordingly

Related

How to get a table data element using the id?

I can't seem to grab the inner text of an element. I have tried many approaches to this and still can't fully understand why this is not working.
I have already tried grabbing it by the class, by the id and even by the type of element.
I expected the function to run, but instead it gets caught in the problem areas I marked within the javascript.
function updateCartTotal() {
var cartItemContainer = document.getElementById('cart-table')
var cartRows = cartItemContainer.rows.length
var total = 0
for (var i = 1; i < cartRows; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementById('item-total')[0] //this is the issue ALSO: i have tried removing "[0]"
var quantityElement = cartRow.getElementsByClassName('form-control')[0] //this is the issue ALSO: i have tried removing "[0]"
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total + (price * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}
<table class="table table-striped table-border checkout-table" id="cart-table">
<tbody>
<tr>
<td class="hidden-xs">
<img src="images/intro-04.jpg" alt="[Rainbow Six] Complete Edition" />
</td>
<td>
<h5 class="txt25">[Rainbow Six] Complete Edition</h5>
</td>
<td class="txt25" id="item-total">
$45.00
</td>
<td>
<input class="form-control" type="number" name="" value="1" max="50" min="1" />
</td>
<td class="item-total-total txt25">
$45.00
</td>
<td><button class="btn btn-danger" onclick="removeRow(this)" type="button">REMOVE</button></td>
</tr>
</tbody>
</table>
getElementById is only on document, not other nodes
document.getElementById('item-total') will return ONE element and
IDs must be unique.
I changed <td class="txt25" id="item-total"> to <td class="txt25 item-total">
I also suggest you change class="cart-total-price" to id="cart-total-price" since there is likely only one
Try classes and querySelector which is superior to getElementsByClassName:
function updateCartTotal() {
[...document.querySelectorAll('cart-table tbody tr')].forEach((cartRow) => {
var price = cartRow.querySelector('.item-total').innerText.replace(/[$\s]/g,"")
var quantity = cartRow.querySelector('.form-control').value;
total += (+price * +quantity)
});
document.querySelector('.cart-total-price').innerText = '$' + total.toFixed(2)
}
For older browser support you can change first line to
var cartRows = document.querySelectorAll('cart-table tbody tr')
for (var i=0, cartRow;i<cartRows.length; i++) {
cartRow = cartRows[i];

proper arithmetic operation for two function in javascript

I want to have a addition of two sum of function to get a overall total. but in return they are just combine in one or the results return NAN.
//function for display
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("₱" ,"") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("₱" ,"");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html("₱" +total);
//$('#total').html("₱"+total);
}
function update_balance() {
var tax = $("#subtotal").html().replace("₱" ,"") * (0.12);
tax = roundNumber(tax,2);
$('.tax').html("₱" +tax);
}
function update_ftotal() {
var sub , ax = 0;
var sub = $("#subtotal").html();
var ax = $('.tax').html();
var due = sub + ax
// due = roundNumber(due,2);
$('.due').html(due);
}
here's the frontend where i use the class and id in the function
<tr>
<td colspan="3" class="blank"> </td>
<td colspan="3" class="total-line">Subtotal:</td>
<td class="total-value"><div id="subtotal" name="subtotal"></div></td>
</tr>
<tr>
<td colspan="3" class="blank"> </td>
<td colspan="3" class="total-line">12% Tax:</td>
<td class="total-value"><div class="tax" id="tax"></div></td>
</tr>
<tr>
<td colspan="3" class="blank"> </td> <!-- add tax result to the subtotal to get final total -->
<td colspan="3" class="total-line balance">Total:</td>
<td class="total-value balance"><div class="due" id="due"></div></td>
</tr>
the result
enter image description here
sub and ax are strings, thus the plus operator concatenates them.
Try this:
var due = parseFloat(sub) + parseFloat(ax);
The answer.
function update_ftotal() {
var sub , ax = 0;
var sub = $(".subtotal").html();
var ax = $(".tax").html();
var num1 = Number(sub);
var num2 = Number(ax);
var due = num1 + num2;
due = roundNumber(due,2);
$('.due').html(due);
}

Multiple countdown timers comparing a given time and current time?

Really struggling with this part for some reason.
I'm creating a timer I can use to keep track of bids. I want to be able to compare two times and have the difference (in minutes and seconds) shown in the countdown column. It should be comparing the bid start time and the time right now.
Perhaps when it reaches bid start it could also change to show how long until bid ends. Eventually I want to add background changes once it's getting close to the time, and perhaps the ablility to set alarms with a prompt window.
Here's the code I have so far:
HTML
<table>
<tr>
<td>Item Name</td>
<td><input id="itemNameField" placeholder="" type="text"></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Time of Notice</td>
<td><input id="noticeField" type="time"></td>
</tr>
</table>
<input id="addButton" onclick="insRow()" type="button" value="Add Timer">
<div id="errorMessage"></div>
<hr>
<div id="marketTimerTableDiv">
<table border="1" id="marketTimerTable">
<tr>
<td></td>
<td>Item Name</td>
<td>Time of Notice</td>
<td>Bid Start</td>
<td>Bid End</td>
<td>Countdown</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div id="itembox"></div>Example Item
</td>
<td>
<div id="noticebox"></div>12:52
</td>
<td>
<div id="bidstartbox"></div>13:02
</td>
<td>
<div id="bidendbox"></div>13:07
</td>
<td>
<div id="countdownbox"></div>
</td>
<td><input id="delbutton" onclick="deleteRow(this)" type="button" value="X"></td>
</tr>
</table>
</div>
JAVASCRIPT
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
if (i == 1) {
console.log = "hi";
} else {
document.getElementById('marketTimerTable').deleteRow(i);
}
}
function insRow() {
if (itemNameField.value == "" || noticeField.value == "") {
var div = document.getElementById('errorMessage');
div.innerHTML = "*Please fill in the fields*";
div.style.color = 'red';
document.body.appendChild(div);
} else {
var div = document.getElementById('errorMessage');
div.innerHTML = "";
var x = document.getElementById('marketTimerTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var inp1 = new_row.cells[1].getElementsByTagName('div')[0];
inp1.id += len;
inp1.innerHTML = itemNameField.value;
itemNameField.value = "";
var inp2 = new_row.cells[2].getElementsByTagName('div')[0];
inp2.id += len;
inp2.innerHTML = noticeField.value;
noticeField.stepUp(10);
var inp3 = new_row.cells[3].getElementsByTagName('div')[0];
inp3.id += len;
inp3.innerHTML = noticeField.value;
noticeField.stepUp(5);
var inp4 = new_row.cells[4].getElementsByTagName('div')[0];
inp4.id += len;
inp4.innerHTML = noticeField.value;
var inp5 = new_row.cells[5].getElementsByTagName('div')[0];
inp5.id += len;
inp5.innerHTML = "";
noticeField.value = "";
x.appendChild(new_row);
}
}
I apologize in advance because my code is probably really messy and badly formatted. Here's a JSFIDDLE as well! Thanks :)
To calculate the difference between the current and given time, you can use setInterval
Example :
var noticeTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
var diffInHours = currentDate.getHours() - noticeTime[0];
var diffInMinutes = currentDate.getMinutes() - noticeTime[1];
inp5.innerHTML = diffInHours + ":" + diffInMinutes;
if(diffInHours === 0 && diffInMinutes === 0) {
clearInterval(interval);
}
},1000)
I managed to do it with the help of the code from ProgXx.
I added the following code:
var noticeTime = noticeField.value.split(":");
var originalTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
noticeTime[1] = originalTime[1] - currentDate.getMinutes() + 10;
noticeTime[1] = noticeTime[1] + (originalTime[0] * 60) - (currentDate.getHours() * 60);
Here's a JSFIDDLE of the finihsed code: http://jsfiddle.net/joefj8wb/

Jquery: calculate volume

Took the base of a code from one user and modified a bit. Basically it does what i need - calculates the sum from three values (first two are in meters, third in centemeters). but i would like it to be more simpler. I dont't need "select options" in thickness field - it must be calculated in centemeters!.
And second request - the amount must be in m3!
html:
<table>
<tbody>
<tr>
<td>Width (m)</td>
<td>
<input type="text" id="width" />
</td>
</tr>
<tr>
<td>Length (m)</td>
<td>
<input type="text" id="length" />
</td>
</tr>
<tr>
<td>Thickness (cm)</td>
<td>
<input type="text" id="thickness" />
</td>
<td>
<select id="sel">
<option>centemeter</option>
<option>meter</option>
<option>melemeter</option>
</select>
</td>
</tr>
<tr>
<td>Total (m<sup>3</sup>)</td>
<td id="answer"></td>
</tr>
</tbody>
</table>
javascript:
$("#width ,#length ,#thickness, #sel").on('change keyup keydown', function() {
var width = $("#width").val();
var length = $("#length").val();
var thickness = $("#thickness").val();
var result = width * length * thickness;
var select_val = $("#sel").val();
if (select_val == "centemeter") {
$("#answer").text(result).append(" cm<sup>3</sup>");;
} else if (select_val == "meter") {
result = result / 100;
$("#answer").text(result).append(" m<sup>3</sup>");;
} else if (select_val == "melemeter") {
result = result * 10;
$("#answer").text(result).append(" mm<sup>3</sup>");
}
});
jsfiddle
update: i thought this will be an easy task: calculate amount of three numbers - something like var result = width * length * thickness; only thickness is 1/100 of width and length...
below solution to my answer. wasn't that complicated, is it?
$("#width ,#length ,#thickness").on('change keyup keydown', function () {
var width = $("#width").val();
var length = $("#length").val();
var thickness = $("#thickness").val();
var result = width * length * thickness;
result = result/100;
$("#answer").text(result).append(" m<sup>3</sup>");;
});
jsfiddle

Using if and else if functions with select inputs (converting results based on km and miles)

I have been trying to build a race predictor calculator based off of Peter Riegel's formula for a couple of days now and have only managed to get it working when the original and future distances are set the same (See below).
However I would like for the user to be able to select kilometres or miles using 'select' and 'options' in the form for both the original and future distance. I have played around with else and else if statements in the script but have completely failed at this. I would greatly appreciate it if someone could help me crack this. (I have put the select and options in already so it is just the scripting that I need help with).
I am completely self taught so I apologise if the code below is a complete mess or incorrect. Thank you! James
function predictorCalc() //Predicting future race results
{
var d1 = document.predictor.d1.value;
var t1 = document.predictor.time1hr.value * 60 * 60 + document.predictor.time1min.value * 60 + document.predictor.time1sec.value * 1;
var deg = document.predictor.deg.value;
var d2 = document.predictor.d2.value;
//NEED TO INPUT IF & ELSE IF STATEMENTS HERE TO MANIPULATE THE RESULT DEPENDING ON WHETHER THE DISTANCE SELECTED IN D1 or D2 is KM OR MILES//
t2 = t1 * (Math.pow((d2 / d1), deg)); //predicted time in seconds (Equation T2=T1*(D2/D1)1.06)
phr = Math.floor(t2/3600); //total hrs
pmin = Math.floor((t2 - (phr*(3600)))/60); //total mins
psec = Math.floor(t2 - (phr*(3600))-(pmin*60)); //total secs
document.predictor.time2hr.value = round(phr,0);
document.predictor.time2min.value = round(pmin,0);
document.predictor.time2sec.value = round(psec,0);
}
function round(x) {
return Math.round(x*100)/100;
}
<form name="predictor">
<table>
<tbody>
<tr>
<td>D1 (Original distance)</td>
<td><input type="text" name="d1" size="3">km</td>
<td>
<select size="1" name="d1units">
<option selected="" value="k">Kilometers</option>
<option value="m">Miles</option>
</select>
</td>
</tr>
<tr>
<td>T1 (original time)</td>
<td><input name="time1hr" size="3" maxlength="2" type="text">hr</td>
<td><input type="text" name="time1min" size="3">min</td>
<td><input type="text" name="time1sec" size="3">sec</td>
</tr>
<tr>
<td>D2 (Future distance competing in)</td>
<td><input type="text" name="d2" size="3">km</td>
<td>
<select size="1" name="d2units">
<option selected="" value="k">Kilometers</option>
<option value="m">Miles</option>
</select>
</td>
</tr>
<tr>
<td>Performance Degradation</td>
<td colspan="3"><input name="deg" size="2" maxlength="4" type="text" value="1.06">(6% or 1.06 as standard)</td>
</tr>
<tr>
<td><input onclick="predictorCalc()" value="Calculate" type="button"></td>
</tr>
<tr>
<td>T2 (Predicted future time)</td>
<td><input name="time2hr" size="3" maxlength="2" type="text">hr</td>
<td><input type="text" name="time2min" size="3">min</td>
<td><input type="text" name="time2sec" size="3">sec</td>
</tr>
</tbody>
</table>
</form>
function predictorCalc() //Predicting future race results
{
const kmPerMile=1.60934;
var d1u = document.predictor.d1units;
var d1units = d1u.options[d1u.selectedIndex].value;
var d1 = d1units=='k'?document.predictor.d1.value:document.predictor.d1.value*kmPerMile;
var d2u = document.predictor.d2units;
var d2units = d2u.options[d2u.selectedIndex].value;
var d2 = d2units=='k'?document.predictor.d2.value:document.predictor.d2.value*kmPerMile;
var t1 = document.predictor.time1hr.value * 60 * 60 + document.predictor.time1min.value * 60 + document.predictor.time1sec.value * 1;
var deg = document.predictor.deg.value;
//NEED TO INPUT IF & ELSE IF STATEMENTS HERE TO MANIPULATE THE RESULT DEPENDING ON WHETHER THE DISTANCE SELECTED IN D1 or D2 is KM OR MILES//
t2 = t1 * (Math.pow((d2 / d1), deg)); //predicted time in seconds (Equation T2=T1*(D2/D1)1.06)
phr = Math.floor(t2/3600); //total hrs
pmin = Math.floor((t2 - (phr*(3600)))/60); //total mins
psec = Math.floor(t2 - (phr*(3600))-(pmin*60)); //total secs
document.predictor.time2hr.value = round(phr,0);
document.predictor.time2min.value = round(pmin,0);
document.predictor.time2sec.value = round(psec,0);
}

Categories

Resources