change div content based on three for elements - javascript

Hey guys,
I'm new to jQuery/js and having a hard time figuring this out.
There are two fields in a form of mine i want to do some calculations with, what i tried is this:
jQuery.fn.calculateit = function(){
var one = $("#one").val();
var two = $("#two").val();
//total
var total = one + two;
$("#total").text(total);
};
The values "one" and "two" can change at any time, and every time that happens i want the total to change. So I wrote the method above, but I have no idea how to have it called any time something happens with the two fields.
Any ideas?
Maybe I'm on the wrong track, so any suggestions are welcome!
Thanks!

Here you go:
$("#one, #two").change(function() {
calculateit();
});
var calculateit = function() {
var one = parseInt($("#one").val(), 10);
var two = parseInt($("#two").val(), 10);
//total
var total = one + two;
$("#total").text(total);
};
Or, if you prefer, you can add calculateit to jQuery.fn and call it with $.calculateit().
Or, more concisely:
$("#one, #two").change(function() {
var one = parseInt($("#one").val(), 10);
var two = parseInt($("#two").val(), 10);
//total
var total = one + two;
$("#total").text(total);
});

Related

Javascript count two variables goes wrong

I am busy with making a kind of invoice system, where the user can make invoices very easily. Now I am at the point where I have to count up, per product, three different variables/items, but instead of counting them up, my javascript code puts it like text (with the + operator).
Example:
selectmenu 1 = option 0 (where VAT = 8.50 euro's)
selectmenu 2 = option 1 (where VAT = 12.76 euro's)
Now the output has to be (8.50+12.76)= 21.26
The output in my situation is = 8.5012.76
My (partial) javascript code:
$("select#product").on("change", function (e) {
var $row = $(e.target).closest('.productitem');
var selVal = $row.find('#product').val();
var totalvat;
var currentVat = $('#totalvat').val();
var NLhoog = 1.21;
var price0EXC = 40.49;
var price0INC = (price0EXC * NLhoog).toFixed(2);
var price0VAT = (price0INC - price0EXC).toFixed(2);
var price1EXC = 60.74;
var price1INC = (price1EXC * NLhoog).toFixed(2);
var price1VAT = (price1INC - price1EXC).toFixed(2);
if (selVal === "0") {
$row.find("input#vat").val(price0VAT);
$row.find("input#priceEXC").val(price0EXC);
$row.find("input#priceINC").val(price0INC);
totalvat = (currentVat + price0VAT);
$('input#totalvat').val(totalvat);
} else if (selVal === "1") {
$row.find("input#vat").val(price1VAT);
$row.find("input#priceEXC").val(price1EXC);
$row.find("input#priceINC").val(price1INC);
totalvat = currentVat+price1VAT;
$('input#totalvat').val(totalvat);
}
});
I have let the unimportant part of the code away.
If you know what I am doing wrong, please let me know :)
Think this may help?
var currentVat = parseFloat($('#totalvat').val());
You are using var currentVat = $('#totalvat').val(); to get the value from an input I assume? This is a string which will need to be parsed at some to a relevant datatype. When + is used with a string the compiler performs concatenation.
Try something like:
var currentVat = parseFloat($('#totalvat').val());
Or do it later on with:
parseFloat(currentVat);
As you're using numbers as currency I'd consider adding the suffix .ToFixed(2) at the end, and maybe some other formatting

Javascript cost calculator wont work as supposed

Hello I am new to Js and I want to make a cost calculation function. So far it works but Its not what I want to have. Here is how it looks
<script>
function finalCost(){
var roomType = document.getElementById("roomtype").value;
var roomNum = document.getElementById("rooms").value;
var personNum = document.getElementById("atoma").value;
var childNum = document.getElementById("paidia").value;
var resFacilities =
document.getElementById("meal").value;
var atoma = childNum + personNum;
var roomty = (parseInt(roomType));
var total = +roomty + +atoma + +((resFacilities));
document.getElementById("result").innerHTML = total;
}
</script>
However, I want to have something like that: ( It wont work I know)
<script>
function finalCost(){
var roomType = document.getElementById("roomtype").value;
var roomNum = document.getElementById("rooms").value;
var personNum = document.getElementById("atoma").value;
var childNum = document.getElementById("paidia").value;
var resFacilities =
document.getElementById("meal").value;
var atoma = childNum + personNum;
var roomty = (parseInt(roomType));
var total = +roomty*roomNum + +atoma + +((resFacilities)*atoma);
document.getElementById("result").innerHTML = total;
}
</script>
If I enter the above code the cost wont work at all If i enter it without the *roomNum the cost will work without the meal included.
Please give me some advice as I am really frustrated by this issue.
If i understand this correctly because I'm unsure of the exact calculation you are trying to compute:
// Total calculated as room type times number of rooms times number of people.
// Adding meal costs per person.
var total = roomty*roomNum*atoma +(resFacilities*atoma);
Your code is working fine please see console output
Of this is not what you looking for. Put your html, javascript somewhere at one place. Where you code can be executed.

JQuery click event only working first time

I am trying to make a dial pad just for the heck of it, the only problem I have ran into so far is that when a key is clicked it will put the corresponding number in the input box, but it won't put another one after that. I have looked at a lot of other posts, because other people have the same problem, but it seems that none of those solutions relate to my problem. Thanks in advance!
The "1" button is the only one I have functioning right now because I am waiting to implement the others until I fix my problem.
var inp = $('#dialer');
var nmbr = inp.val();
var key1 = $('#111');
key1.on('click', function(){
inp.val(nmbr + 1)
});
JSfiddle: https://jsfiddle.net/a4suk0rs/
This is because you're setting var nmbr = inp.val(); only once, so that variable will only ever contain the elements' initial value. Change your code to this:
var inp = $('#dialer');
var nmbr = inp.val();
var key1 = $('#111');
key1.on('click', function(){
nmbr = inp.val(); // reset the `nmbr` var to the current value of `$('#dialer')`
inp.val(nmbr + 1)
});

jquery: Adding up numbers to the current value?

I'm trying to add up numbers to the current value. what I am trying to do is almost a simple shopping cart using jQuery.
However, the issue that I am facing is that the numbers wont add up at all. but instead the numbers get replaced by the new one!
And in fact, I get some strange behavior!
To explain this better I've created this FIDDLE
My code is:
$('.addons').click(function() {
var price2 = +$(this).attr('data-price');
$('#fuelcellprice').val(price2);
var inputval = +$('#fuelcellprice').val();
var finaltotal = price2 + inputval;
alert(finaltotal);
});
Could someone please advise on this issue?
If #fuelcellprice stores your sum, set it at the very end of your handler. Don't use +, which is misleading for the purpose. I recommend you to rename your variables to reflect your intent accordingly:
$('.addons').click(function() {
var itemPrice = $(this).attr('data-price');
var currentSum = $('#fuelcellprice').val();
var sum = itemPrice + currentSum;
$('#fuelcellprice').val(sum); //store your final value here
alert(sum);
});
1st you need to use parseFloat()
2nd I don't know why you use $('#fuelcellprice').val() while you set it to price2
try this
var inputval = 0;
$('.addons').click(function() {
var price2 = parseFloat($(this).attr('data-price'));
$('#fuelcellprice').val(price2);
inputval += price2;
alert(inputval);
});
Working Demo

Using one javascript function for multiple inputs on one form

We have a simple age calculating script, that takes a date input (3 selects - day, month, year) and determine how old. It is triggered by an onChange assigned to the year select.
There are several date inputs scattered through the form, each one set up the same, other than the input names (day1 vs day 1 vs day 3, etc).
Currently we have simply duplicated the js code and manually changed the input variables ...
function Age1()
{
var oldDay = document.step1.day1.value;
var oldMonth = document.step1.month1.value;
var oldYear = document.step1.year1.value;
and more script....
function Age2()
{
var oldDay = document.step1.day2.value;
var oldMonth = document.step1.month2.value;
var oldYear = document.step1.year2.value;
and more script....
and so forth.
Ideally we would like to reuse one script, rather than hardcoding one for each instance. I have tried a bunch of ideas to no avail, but the ideal would be to trigger it via: onChange="Age(X);" and then have the js insert the proper variable:
function Age(varX)
{
var oldDay = document.step1.dayX.value;
var oldMonth = document.step1.monthX.value;
var oldYear = document.step1.yearX.value;
and so on ....
Any ideas for us ? Thanks in advance
function Age(varX)
{
var oldDay = document.step1['day' + varX].value;
var oldMonth = document.step1['month' + varX].value;
var oldYear = document.step1['year' + varX].value;
}

Categories

Resources