How would I create a currency converter with javascript? - javascript

I'm trying to build a currency converter. I'm using javascript and I have a good foundation but I want to know how to make the converter update in real-time without having to click a button.
How do I make it so that my converter converts from a base currency of M without needing be be within a select element & how do I make the converter update as the user types the number in, rather than having to click a button?
I've tried removing all of the available options for the .currency-1 class and only leaving M, but that still leaves a drop down menu. I want to convert from M to X (USD, GBP, CAD, EUR, etc.)
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
Any help would be appreciated!
I need the user to be able to input X amount (in currency M, no dropdown), select their native currency & have the page calculate the rate as soon as they type in the number.

Add another eventListner which is keyup so that whenever user types in the required field, it will call the convertCurrency function as below:
amountInput.addEventListener('keyup', convertCurrency);
Edit:
To remove the selection box for M, remove the select element and replace by either <p> or <span> tag. After this, you would have to get the this value by using innerText as var from = baseCurrencyInput.innerText; in the currency converter function.
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
}
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.innerText;
var to = secondCurrencyInput.value;
var result = 0;
try {
if (from == to) {
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch (err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
amountInput.addEventListener('keyup', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<p id="currency-1">M</p>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>

var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
$('#amount').keyup(function(event){
convertCurrency(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>

Related

Plus and Minus Algorithm not working (JavaScript)

I have two buttons labeled plus and minus side by side and a display box at the center. I have a fixed value box at the top (say 10). When a user clicks plus the display box becomes one while the fixed value reduced to 9 and if I click the minus button, the fixed value returns to 10 while the display value becomes 0... It continues like that until the fixed value is exhausted. The functionality should work for all my four inputs. Below is what have tried.
var minusBtn = document.querySelectorAll("#minus");
var plusBtn = document.querySelectorAll("plus");
var displayvalue = document.querySelectorAll("displayvalue");
var number = 0;
var min = 0;
var fixed = 10;
plusBtn.onclick = function() {
if (fixed > number) {
number = number++;
numberPlace.innerText = number; /// Display the value in place of the number
}
if (number == max) {
} else {
}
}
<body>
<div class="Fixed_number">10</div>
<form>
<label for=""> One
<div id="">
<button id="plus">+</button>
<span id="displayvalue">0</span>
<button id="minus">-</button>
</div>
</label>
</form>
<form>
<label for=""> Two
<div id="">
<button id="plus">+</button>
<span id="displayvalue">0</span>
<button id="minus">-</button>
</div>
</label>
</form>
<form>
<label for=""> Three
<div id="">
<button id="plus">+</button>
<span id="displayvalue">0</span>
<button id="minus">-</button>
</div>
</label>
</form>
<form>
<label for=""> Four
<div id="">
<button id="plus">+</button>
<span id="displayvalue">0</span>
<button id="minus">-</button>
</div>
</label>
</form>
<link rel="stylesheet" href="app.js">
</body>
If you must do it like this than change JS to
var total = document.querySelector(".Fixed_number");
var minusBtn = document.querySelectorAll("#minus");
var plusBtn = document.querySelectorAll("#plus");
plusBtn.forEach(function(item){
item.onclick = function(){
if( parseInt(total.innerText) > 0 ){
item.nextElementSibling.innerText = parseInt(item.nextElementSibling.innerText) + 1;
total.innerText = parseInt(total.innerText) - 1;
}
};
});
minusBtn.forEach(function(item){
item.onclick = function(){
if( parseInt(item.previousElementSibling.innerText) > 0 ){
item.previousElementSibling.innerText = parseInt(item.previousElementSibling.innerText) - 1;
total.innerText = parseInt(total.innerText) + 1;
}
};
});
And you must put type="button" for all buttons or else it will submit the form and reload the page.

how to delete the inserted row by the delete button

I am trying to delete the entered task by the delete button which is created by the end of each task. I am posting my full code here
It's a simple to-do list by using bootstrap CDN .
I want to delete the row which contains user enter task,serial number,time and date.
var task = document.getElementById("enter");
var bttn = document.getElementById("button2");
var rowIdVar = document.getElementById("test");
var rowIdVar1 = document.getElementById("id1");
bttn.addEventListener("click", add);
var x = 0;
function add() {
var val1 = task.value;
if (!val1) {
alert("Please Enter A Task");
} else {
sno();
name();
tdate();
time();
cButton();
var new1 = document.createElement("l");
rowIdVar1.appendChild(new1);
}
}
function sno() {
if (x == x) {
x = x + 1;
var list1 = document.createElement("l");
list1.innerHTML = x;
rowIdVar.appendChild(list1).setAttribute("class", "col-md-2");
}
}
function name() {
var val = task.value;
var list2 = document.createElement("l");
list2.innerHTML = val;
rowIdVar.appendChild(list2).setAttribute("class", "col-md-4");
task.value = "";
}
function tdate() {
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var result = (date + "/" + month + "/" + year);
var lm = document.createElement("l");
lm.innerHTML = result;
rowIdVar.appendChild(lm).setAttribute("class", "col-md-2");
}
function time() {
var t = new Date();
var hour = t.getHours();
var minutes = t.getMinutes();
var seconds = t.getSeconds();
var result1 = (hour + ":" + minutes + ":" + seconds);
var lm1 = document.createElement("l");
lm1.innerHTML = result1;
rowIdVar.appendChild(lm1).setAttribute("class", "col-md-2");
}
function cButton() {
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "delete");
btn.setAttribute("class", "btn btn-danger");
rowIdVar.appendChild(btn).setAttribute("class", "col-md-2");
btn.addEventListener("click", deleteElements);
}
function deleteElements() {
rowIdVar1.parentNode.removeChild(rowIdVar);
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<div class="row">
<div class="col-md-10 col-sm-10 h">
<center>
<h1>TO DO LIST...</h1>
</center><br>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-sm-10 bg">
<input type="text" class="form-control " placeholder="Enter task" id="enter">
</div>
<div class="col-md-2 col-sm=2">
<button type="button" class="btn btn-primary btn-lg" id="button2"><center>ADD</center></button>
</div>
</div><br><br>
</div>
<div class="container">
<div class="row" id="id1">
<div class="col-md-2 b">
<h1>S.no</h1>
</div>
<div class="col-md-4 b">
<h1>Enter Task</h1>
</div>
<div class="col-md-2 b">
<h1>Date</h1>
</div>
<div class="col-md-2 b">
<h1>Time</h1>
</div>
<div class="col-md-2">
</div>
</div>
</div>
<div class="row" id="test">
<div class="col-md-2"> </div>
<div class="col-md-4"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
</div>
var task = document.getElementById("enter");
var bttn = document.getElementById("button2");
var rowIdVar = document.getElementById("test");
var rowIdVar1 = document.getElementById("id1");
bttn.addEventListener("click", add);
var x = 0;
function add() {
var val1 = task.value;
if (!val1) {
alert("Please Enter A Task");
} else {
sno();
name();
tdate();
time();
cButton();
var new1 = document.createElement("l");
rowIdVar1.appendChild(new1);
}
}
function sno() {
if (x == x) {
x = x + 1;
var list1 = document.createElement("li");
list1.innerHTML = x;
rowIdVar.appendChild(list1).setAttribute("class", "col-md-2");
}
}
function name() {
var val = task.value;
var list2 = document.createElement("li");
list2.innerHTML = val;
rowIdVar.appendChild(list2).setAttribute("class", "col-md-4");
task.value = "";
}
function tdate() {
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var result = (date + "/" + month + "/" + year);
var lm = document.createElement("li");
lm.innerHTML = result;
rowIdVar.appendChild(lm).setAttribute("class", "col-md-2");
}
function time() {
var t = new Date();
var hour = t.getHours();
var minutes = t.getMinutes();
var seconds = t.getSeconds();
var result1 = (hour + ":" + minutes + ":" + seconds);
var lm1 = document.createElement("li");
lm1.innerHTML = result1;
rowIdVar.appendChild(lm1).setAttribute("class", "col-md-2");
}
function cButton() {
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "delete");
btn.setAttribute("class", "btn btn-danger");
rowIdVar.appendChild(btn).setAttribute("class", "col-md-2");
btn.addEventListener("click", deleteElements);
}
function deleteElements() {
rowIdVar.parentNode.removeChild(rowIdVar);
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<body id="body">
<div class="row">
<div class="col-md-10 col-sm-10 h">
<center>
<h1>TO DO LIST...</h1>
</center><br>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-sm-10 bg">
<input type="text" class="form-control " placeholder="Enter task" id="enter">
</div>
<div class="col-md-2 col-sm=2">
<button type="button" class="btn btn-primary btn-lg" id="button2"><center>ADD</center></button>
</div>
</div><br><br>
</div>
<div class="container">
<div class="row" id="id1">
<div class="col-md-2 b">
<h1>S.no</h1>
</div>
<div class="col-md-4 b">
<h1>Enter Task</h1>
</div>
<div class="col-md-2 b">
<h1>Date</h1>
</div>
<div class="col-md-2 b">
<h1>Time</h1>
</div>
<div class="col-md-2">
</div>
</div>
</div>
<div class="row" id="test">
<div class="col-md-2"> </div>
<div class="col-md-4"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
</div>

Trying to remove each line of HTML element using a newly created button

var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var IncomeList = document.getElementById("incomeList");
var ExpenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
var DButton = document.createElement("button");
var t = document.createTextNode("Delete");
//document.body.appendChild(DButton);
DButton.appendChild(t);
// Converts the fake (non-existant)numbers into real (functionable) numbers
var aValue = parseFloat(Amount.value);
// if the operator is +, budget and income will increase by whatever you type in the value
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
// The value that was typed along with description in will appear in the Income list in each line
IncomeList.innerHTML = IncomeList.innerHTML + Desc.value + ": " + aValue;
IncomeList.appendChild(DButton);
IncomeList.innerHTML = IncomeList.innerHTML + "<br>";
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
ExpenseList.innerHTML = ExpenseList.innerHTML + Desc.value + ": " + aValue;
ExpenseList.appendChild(DButton);
ExpenseList.innerHTML = ExpenseList.innerHTML + "<br>";
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget;
document.getElementById("incomeTotal").innerText = income;
document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>
Hi, this is a budget tracker I made to practice JavaScript. So whenever users type a description and an amount and press submit, the list will show up along with a delete button that erases each line. How should I approach this method? Because the button is newly created by createElement, I do not know how to make this a handler...Thank you.
Append a row container instead of concatenating to the HTML string, and then you can attach a listener to the button that calls .remove() on the row.
It's often a good idea to avoid assigning to innerHTML when possible - it will corrupt all existing Javascript references to any elements inside. If you want to assign text alone, use textContent rather than innerHTML or createTextNode. (it's faster, safer, and more predictable)
var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var incomeList = document.getElementById("incomeList");
var expenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
const parent = Operator.value === "+" ? incomeList : expenseList;
const row = parent.appendChild(document.createElement('div'));
var DButton = row.appendChild(document.createElement("button"));
DButton.textContent = 'delete';
DButton.onclick = () => row.remove();
var aValue = parseFloat(Amount.value);
row.appendChild(document.createTextNode(Desc.value + ": " + aValue));
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget; document.getElementById("incomeTotal").innerText = income; document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>

why my calculations are not correct

I have an HTML form and a Javascript but this Javascript performs an incorrect calculation
function hitung(){
var e = (document.getElementById("ifin").value);
var panjang = parseFloat (document.getElementById("ipanjang").value);
var tinggi = parseFloat (document.getElementById("itinggi").value);
var ht = 2.0;
var hf = 0.0;
var total = 0.0;
if (e == "hpl") {
hf = 0.0;
}
else if (e == "cat") {
hf = 0.5;
}
else {
hf = 0.0;
}
total = panjang*tinggi*ht+hf;
document.getElementById("ototal").innerHTML =
"Harga Total : Rp." + total.toFixed(2) + "0.000,00" + "<br>Sudah termasuk ongkir";
<select name="ifin" id="ifin" class="form-control input-lg" required >
<option selected disabled >Select Finishing</option>
<option value="hpl">HPL</option>
<option value="cat">Cat Duco</option>
</select>
<br>
<h3 align="center"> Masukkan Ukuran </h3>
<div class="form-group row">
<div class="col-xs-6" align="center">
<input class="form-control" type="number" placeholder="Panjang" min="1" id="ipanjang" >
</div>
<div class="col-xs-6">
<input class="form-control" type="number" placeholder="Tinggi" min="1" id="itinggi">
</div>
</div>
The result is not what I wanted, the hf does not count, which counts only panjang*tinggi*hf
I believe something wrong with your
var e = document.getElementById("ifin").value;
Try exclude the bracket.
You must select the select tag first then extract the valid option
var e = document.getElementById("ifin")
var rm = e.options[e.selectedIndex].value
if(rm == "hpl") {//do stuff}
function hitung(){
var e = (document.getElementById("ifin").value);
var panjang = parseFloat (document.getElementById("ipanjang").value);
var tinggi = parseFloat (document.getElementById("itinggi").value);
var ht = 2.0;
var hf = 0.0;
var total = 0.0;
if (e == "hpl") {
//hf = 0.0;
hf = 1.0;//I wanted 3rd value to make sure it works
}
else if (e == "cat") {
hf = 0.5;
}
else {
hf = 0.0;
}
document.getElementById("hf").innerHTML = "HF = " + hf;
total = panjang*tinggi*ht+hf;
document.getElementById("ototal").innerHTML =
"Harga Total : Rp." + total.toFixed(2) + "0.000,00" + "<br>Sudah termasuk ongkir";
}
<select name="ifin" id="ifin" class="form-control input-lg" required >
<option selected disabled >Select Finishing</option>
<option value="hpl">HPL</option>
<option value="cat">Cat Duco</option>
</select>
<br>
<h3 align="center"> Masukkan Ukuran </h3>
<div class="form-group row">
<div class="col-xs-6" align="center">
<input class="form-control" type="number" placeholder="Panjang" min="1" id="ipanjang" >
</div>
<div class="col-xs-6">
<input class="form-control" type="number" placeholder="Tinggi" min="1" id="itinggi">
</div>
</div>
<button onclick="hitung()">Calculate</button>
<h2 id="ototal"></h2>
<h2 id="hf"></h2>
Your code looks fine for me, I added a button calculate that will output the value along with hf, run the snippet and choose the values and press calculate, you'll see the value.
did you try change the value of hf? it says that the value of hf is floating point value or zero values. change that to non-negative value then try it again

Javascript percentage calculation for each form field

I'm trying to work out the percentage value for each field in a form. However my current code is only working out the value for the first field or whichever one is focused.
I'd like it so that the percentage value only for the filed in the same fieldset
The current code works but i'd like to apply to to multiple fieldsets without them interfering with other inputs on the same page
In the snippet you can see that the two separate amounts which are editing each others details
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$($percentage).add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var percentage = parseFloat($(this).val());
var price = parseFloat($price.val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$increase.text(newPrice);
$increaseWrap.fadeIn();
if (isNaN(newPrice)) {
$increaseWrap.hide();
}
}
function calculatePerc() {
var percentage = $percentage.val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$increase.text(newPrice);
}
function removePercent() {
$increaseWrap.fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 1</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[0]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 2</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[1]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="13005.02" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage2">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage2">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
Instead of IDs, use classes and DOM traversal functions to find the fields in the same fieldset.
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$percentage.add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var $fieldset = $(this).closest("fieldset");
var percentage = parseFloat($(this).val());
var price = parseFloat($fieldset.find(".form-item--invamt .form-item__input").val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
$fieldset.find(".wrapper-types__percentage").fadeIn();
if (isNaN(newPrice)) {
$fieldset.find(".wrapper-types__percentage").hide();
}
}
function calculatePerc() {
var $fieldset = $(this).closest("fieldset");
var percentage = $fieldset.find(".form-item__input-expand .percentage").val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
}
function removePercent() {
var $fieldset = $(this).closest("fieldset");
$fieldset.find(".wrapper-types__percentage").fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>

Categories

Resources