JS - Calculate values depending on selected dropdowns - javascript

So I have this calculator for money that shows you the amount you enter but in a different money value. (Example dollar to euro)
Here is the HTML:
<b> Exchange money </b> <br> <br>
Enter amount for RSD: <input type="number" name="nbsAmount" id="nbsAmount" size="5"> <br>
<button class="dugme">Calculate</button> <br> <br>
Evro value is: <div class="konacnaEvroVrednost"></div>
Dolar value is: <div class="konacnaDolarVrednost"></div>
Swiss value is: <div class="konacnaSwissrednost"></div>
And here is the JS:
$('.dugme').click(function(){
var broj = document.getElementById('nbsAmount').value;
var evro = broj * 0.0085;
var dolar = broj * 0.0095;
var frank = broj * 0.0096;
$('.konacnaEvroVrednost').text(evro + ' €');
$('.konacnaDolarVrednost').text(dolar + ' $');
$('.konacnaSwissrednost').text(frank + ' Fr');
});
And this works fine. As you can see:
Here is the fiddle:
http://jsfiddle.net/5zvdwtpL/1/
But now I want to change this to work a bit more dynamically.
I want there to be two dropdowns that lets you select the value you want to change from to. Like this:
This is what I got so far: https://jsfiddle.net/7s8g9kLt/2/
The problem is that one input value should be copied to the other input value but with the added value of the currency.
So If I select RSD and set 1200, the other USD, then the other input should display 11.4.
So I am stuck a bit here as to how I can achieve this.

First of all, you have bound myFunction to button onClick Event but you have not defined function with this name. You can see following error in console after clicking button
Uncaught ReferenceError: myFunction is not defined
You will have to define this function:
window.myFunction = function() {...}
or event better, add event listener to button click:
document.getElementById('buttonId').addEventListener('click', function() {...})
To calculate dynamic rates, i would first convert input amount to single currency (for example RSD) and then multiply that value by correct rate.
I've modified your jsFiddle (https://jsfiddle.net/rhj4dgz7/3/) to reflect those changes.

You can create a dictionary with the pair of "id" of dropdown and the conversion rate, also you can give the same id to both drop downs. then you gonna just multiply the value by the rate and add the result to the second input.
var rsd = 1;
var evro = 0.0085;
var dolar = 0.0095;
var frank = 0.0096;
var dict = {
"4":rsd,
"1":evro,
"3":dolar,
"2":frank
}
function myFunction(){
var mvs = document.getElementById('mojaVrednostSelect').value;
var nvs = document.getElementById('novaVrednostSelect').value;
var mv = document.getElementById('mojaVrednost').value;
var nv = document.getElementById('novaVrednost').value;
novaVrednost.value = parseInt(mojaVrednost.value) * dict[nvs]
console.log("Yoooo"+ dict[nvs])
console.log("mvs je" + mvs);
console.log("nvs je" + nvs);
console.log("======");
console.log("mojaVrednost je" + mojaVrednost.value);
console.log("novaVrednost je" + novaVrednost.value);
}
document.getElementById('button').onclick = myFunction
check this fiddle
Hope this helps you

Related

Attempting energy volume conversion in JS & HTML, getting 0

Objective: Looking to build an script which enables 'therm' to be converted to 'MWh'. In order to do so, the user would fill out the 'therm' input box, click the 'convert' button and the 'MWh' value should appear below.
Currently the code I have written is as follows:
<p>Therm: <input type="number" id="thermid" name="therminput" /></p>
<p> MWh: <span id="MWhid"></span></p>
<p><input type="button" value="Submit" id="convertbutton" /></p>
<script>
var therm = document.getElementById("thermid").value; //This identifies the input field for therm
var MWh = therm * 0.029307; //This determines the conversion from therm to MWh - something is wrong here
//Below identifies when the button is clicked (eventlistener) then the 'innerHTML' displays the var MWh in the HTML field
document.getElementById("convertbutton").addEventListener("click", function () {
document.getElementById("MWhid").innerHTML = MWh;
})
</script>
Problem: The result is 0 regardless of the value that the user enters in the 'therm' field and I believe this is resulting from where var MWh is being determined. I don't appear to be able to get this correct. Could someone give me a hand?
Many thanks in advance,
Ralph
You are not updating the calculation every time the button is clicked. The only time the following lines of code are run:
var therm = document.getElementById("thermid").value;
var MWh = therm * 0.029307;
are on the document load. Simply place them inside the event handler, so that their values get updated every time you click the button. I.e.:
document.getElementById("convertbutton").addEventListener("click", function () {
var therm = document.getElementById("thermid").value;
var MWh = therm * 0.029307;
document.getElementById("MWhid").innerHTML = MWh;
})

Javascript OOP: Passing a value to property through input fails

I`m learning and training js oop right now but I have an issue. I want to pass a value to property from a constructor by input value.For example if the user want to make his own character , he has to input name , age ,etc etc... but my code fails.Here's my js and html code.I've searched for the answer in the stackoverflow but couldn't find any answers to my question.
JS
document.addEventListener("DOMContentLoaded", function() {
var button = document.getElementById('action');
var nameInput = document.getElementById('charName').value;
var ageInput = document.getElementById('age').value;
var par = document.getElementById('result');
function Person(name,age){
this.name = name;
this.age = age;
}
var first = new Person(nameInput,ageInput);
button.addEventListener('click',function(){
par.innerHTML = first.name + ' ' + first.age;
});
});
HTML:
<h1>Javascript Found</h1>
<button id="action">Action</button>
<div id="holder">
<p>
Give a name:<input type="text" id="charName" placeholder="Enter a name">
</p>
<p>
Enter age: <input type="text" id="age" placeholder="Enter a number(0-100)">
</p>
<p id="result"></p>
</div>
I would assume that the click listener is executed correctly, but the values of first.name and first.age are ''. You can verify that by putting a console.log(first) in the click listener.
So why is that? At the time your DOMContentLoaded listener triggers, both your inputs are empty (value == ''). Now, you copy these values into an instance of Person. Next, you wait for clicked events which are triggered at some point but the value of name and age in your instance were not updated so they are still "". So you set par.innerHTML = ' '.
What you need to do is, you have to read the values of your inputs again and update the variables in your instance before you set par.innerHTML.
You need to grab the value from the input on click not before that otherwise it will use the old value which would be an empty string.
I changed the code so nameInput and ageInput refer to the elements and the value is then fetch inside the Person class and first is created on click.
See JSFiddle to see it working.
var button = document.getElementById('action');
var nameInput = document.getElementById('charName');
var ageInput = document.getElementById('age');
var par = document.getElementById('result');
function Person(name,age){
this.name = name.value;
this.age = age.value;
}
button.addEventListener('click',function(){
var first = new Person(nameInput, ageInput);
console.log(first);
par.innerHTML = first.name + ' ' + first.age;
});

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

How to Input a Discount Price in Javascript?

The Discount field does not register
(discount is supposed to subtract from Grand Total)(check discount sample)
check the the jsfiddle click here
I want it to act like this picture. (with the discount being manually inputed) http://i.dailymail.co.uk/i/pix/2013/02/07/article-2275089-17694138000005DC-460_634x497.jpg
Javascript
function recordToFilename() {
var input = document.getElementById('discountvalue'),
discount12 = input.value;
Change your button to
<input type="button" onclick="recordToFilename();" value="Submit Discount" />
And function
function recordToFilename() {
var input = document.getElementById('discount'),
discount12 = input.value;
alert (discount12);
}
you have 2 id="discount". Change one of the id and the there is no problem to register the input value to discount12.
Put this line document.getElementById('discounts').innerHTML = "<strong>Discount </strong>: $" + (salesTotal * 0.14 + salesTotal - discount12).toFixed(2);
in your recordToFilename() method and make sure your variable is chage to discount12 not discount

Strange jquery bug in simple code

I have a simple html code with form:
<span class="price"></span>
Enter amount:
<input type="text" class="form-control amount" name="amount" value="500">
<!--Next input fields are hidden by Bootstrap class "hide"-->
<input type="text" name="minimal-amount" class="hide minimal-amount" value="500">
<input type="text" name="oneprice" class="hide oneprice" value="0.20">
<script>
$(".amount").on("change", function(){
var am = $(".amount").val();
var min = $(".minimal-amount").val()
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
</script>
Idea of this code is very simple. When user put in amount field digits, my script should check, if that, what user put is smaller than minimum available value in minimal-amount field, script changes value of amount field to default minimal-amount.
But the problem is, that id I just add 0 in amount field (and it's value become 5000) everything is ok, but when I changes value of amount field to 1000, script changes value of amount field to default, as if it smaller them minimul-amount.
What I do wrong, and how can I fix this problem?
P.S. Example of this code you can find here - http://friendfi.me/tests/amount.php
You should parse the value before use. Because .val() will return only string type.
$(".amount").on("change", function(){
var am = parseFloat($(".amount").val());
var min = parseFloat($(".minimal-amount").val());
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
There are a lot of gotchas in that code. Here is a working JSBin: http://jsbin.com/qilob/2/edit?html,js,output
Highlights
You need the DOM to be initialized before you can work with it.
Wrapping this in a function passed to jQuery will make it wait till
the page finishes loading before manipulating it.
$(function() { ... });
Use cached values since the elements are not going to change much.
This saves the need to parse the selectors multiple times. It also saves
on typing and readability.
var $amount = $("#amount");
var $minimalAmount = $("#minimal-amount");
var $onePrice = $("#oneprice");
var $finalPrice = $("#price");
When parsing a string to an Int you need to use parseInt
var amount = parseInt($amount.val(), 10);
Conversely when parsing a string to a Float you need to use parseFloat
var price = parseFloat($onePrice.val());
JavaScript can not handle float based arithmetic well.
rounding errors are bad especially when dealing with money we need
to move the decimal place to prevent rounding errors in the more significant
parts of the price value.
var total = (amount * (price * 100)) / 100;
See it in action in the JSBin.

Categories