Looking for a solution to another problem I cam across the ability to run javascript on mouseover
I'd like to run this:
$(document).ready(function(){
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
}
When a user mouses over my submit button
When the script runs I'd like it to populate these fields which are then included in the form action
<input type="hidden" name="repay" id="repay_input" value="">
<input type="hidden" name="interest" id="interest_input" value="">
Right now it doesn't seem to work but this may be because I've missed a small thing or it just won't work entirely
Thank you - If anyone has a better idea on how to achieve my aim please let me know, I've tried PHP but no joy
Button for clarity
<button class="col-sm-4 enter-button" type="submit" name="submit" onmouseover="return myPayment()" value="Calculate">Calculate Payments</button>
Update:
I tweaked the javascript and the button but then missed off naming the form to match the reference in the JS
Also my mortgage calculations were WAY off due to the way the form collects % rate
Declare your function outside of jQuery's document.ready wrapper, and your button only needs to look like this:
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
<button onmouseover="myPayment()" ...></button>
Related
I am trying to code a calculator which will give me a cost per square metre.
At the moment, I have the calculator working and producing a cost for the square meterage, however, what I want to try and do is have if statements, so that if the area comes back less than 15 m², the cost is worked out (area * 2000) and if the area comes back more than 15 m² it is worked out as (area star * 1750)
Any help would be greatly appreciated.
My code is currently
function calculateCost() {
var width = document.getElementById("width").value;
var depth = document.getElementById("depth").value;
var area = width * depth;
var totalCost = area * 2000
document.getElementById("result").innerHTML = "Total cost: £" + totalCost;
}
<form>
Width in Metres: <input type="text" id="width"><br> Depth in Metres: <input type="text" id="depth"><br>
<input type="button" value="Calculate" onclick="calculateCost()">
</form>
<div id="result"></div>
Instead of
var totalCost = area * 2000
write
var totalCost = area * (area <= 15 ? 2000 : 1750);
Now you will have price = area * 2000 for area less or equal than 15, and discount for higher areas.
A few answers were giving using the ternary operator, which were short and succinct, but I would argue they're not the most readable.
Effectively, you have a number (be it 2000 or 1750) that you need to multiply your the area with to get your total cost. You could start off by giving this a name. Say, costMultiplier.
We can assign it with the value 2000 to begin with (which assumes the area is less than 15m2).
var costMultiplier = 2000;
Now, you just need to check if the area is greater than 15m2. And if it is, you update costMultiplier accordingly.
if (area > 15) {
costMultiplier = 1750;
}
Finally, you can update your totalCost like this
var totalCost = area * costMultiplier
If there are any other conditions under which the cost multiplier might change, you could just add an else if branch to the if statement.
You need just to add a condition on the area value:
function calculateCost() {
var width = document.getElementById("width").value;
var depth = document.getElementById("depth").value;
var area = width * depth;
var totalCost = (area < 15) ? area * 2000 : area * 1750;
document.getElementById("result").innerHTML = "Total cost: £" + totalCost;
}
<form>
Width in Metres: <input type="text" id="width"><br> Depth in Metres: <input type="text" id="depth"><br>
<input type="button" value="Calculate" onclick="calculateCost()">
</form>
<div id="result"></div>
I'm using Github pages to host my website currently and my function works perfectly fine on desktop but not on my phone(Ios) and other peoples phone(also Ios).
My function is supposed to calculate how many calories and grams of protein someone needs to maintain/gain/lose weight.
my code
function lbsToProtein(lbs, weightGoal, cm, age, excercise) {
var kgs = lbs / 2.205;
var calorieIntake;
var proteinGrams;
switch (weightGoal) {
case 1: //maintain weight
calorieIntake = (kgs * 13.397) + (cm * 4.799) - (age * 5.677) + 88.362 + excercise;
proteinGrams = kgs * 0.8;
break;
case 2: //gain weight
calorieIntake = ((kgs * 13.397) + (cm * 4.799) - (age * 5.677) + 88.362) + 700 + excercise;
proteinGrams = kgs * 1.35;
break;
case 3: //lose weight
calorieIntake = (((kgs * 13.397) + (cm * 4.799) - (age * 5.677) + 88.362) - 700) + excercise;
proteinGrams = kgs * 0.8;
break;
}
var calorieIntake = Math.round(calorieIntake);
var proteinGrams = Math.round(proteinGrams);
//changed this to 2.55 for now until you add maintaining too
console.log("Protein: "+proteinGrams+"g");
console.log('Calorie Intake: '+calorieIntake+'cal', (typeof calorieIntake));
var info = [proteinGrams, calorieIntake];
console.log(info)
return info;
}
function ftTocm(height) {
console.log(height)
var ft = height.split("'");
//console.log(ft[0], ft[1]);
var cm = ((parseInt(ft[0]) * 12) + parseInt(ft[1])) * 2.54;
console.log("cm", cm);
return cm;
}
function submit() {
var lbs = parseFloat(document.getElementById('lbs-input').value);
var age = document.getElementById('age-input').value;
var height = document.getElementById('height-input').value;
var fat = document.getElementById('fat-input').value;
var goal_input = document.getElementById('select');
var excercise_input = document.getElementById('excercise'); // value given 1 through 3 to switch function
var excercise = excercise_input.value;
var weightGoal = goal_input.value;
var info = lbsToProtein(lbs, parseInt(weightGoal), ftTocm(height), parseInt(age), parseInt(excercise));
document.getElementById('calories').innerHTML = info[1] + ' calories';
document.getElementById('protein').innerHTML = info[0] + ' grams';
document.getElementById('form').style.cssText = 'display: none;';
document.getElementById('results').style.cssText = 'display: block !important;';
}
I've tried switching things from let to var since people have said es6 didn't work on IOS, but that issue was 12 years ago so probably not the problem. Clearing cache also isn't working. Besides that, any tips are helpful. I do have a node module in my website but it's just for animations. I haven't tried it on Android yet either. I've looked at other posts about IOS not working but none seem to fix my issue.
The problem is with your values you are getting in submit() function through id of each element. When you get the value by id the value is in string format, Chrome and Firefox are smart enough to parse this string to Int or double value but Safari considers this an invalid value. you can do this instead:
let info = lbsToProtein(parseFloat(lbs), parseInt(weightGoal), ftTocm(height.toString()), parseInt(age), parseInt(excercise));
Also void using var instead use let
Remove var ft = height.split("'");
replace with
let ft = null;
if(height.indexOf(fapp)>0){
ft = height.split(fapp);
}
else{
ft = height.split('\'');
}
This error occurs because iOS devices have "Smart Punctuation" turned on which was causing split to not work.
I can't seem to finish this. I know how to find out if the number is divisible by 3 but once I get above 3 how do I keep the discount plus the remainder? Example: 7 tickets cost $120
$20 each or 3 for $50
<input id="raffleTix" type="text" value="0" />
if($('#raffleTix').val() % 3 == 0){
raffle = ($('#raffleTix').val() / 3) * 50;
}else if($('#raffleTix').val() < 3){
raffle = $('#raffleTix').val() * 20;
}else{
}
There is no need to have any conditional logic. This can be done with a simple formula:
var value = $('#raffleTix').val();
var setsOfThree = Math.floor(value / 3);
var singles = value - setsOfThree * 3;
raffle = setsOfThree * 50 + singles * 20;
Or even better, it could all be placed in a function so that different values could be passed without modifying the code:
function computeCost(quantity, setSize, setCost, singleCost) {
var sets = Math.floor(quantity / setSize);
var singles = quantity - sets * setSize;
return sets * setCost + singles * singleCost;
}
raffle = computeCost($('#raffleTix').val(), 3, 50, 20);
I am trying to do math with Javascript, it will run calculation from one input (monthly salary) to result (tax) as following:
Deduction from annual income (12000)
here comes the hard part, tax is calculated in different levels, so if annual is between 6500 and 25000, tax should be 10%. And if there is more left after 25000 and less than 40000, tax should be 15% added to the previous 10%, and so on.
EX. if annual is 60000, the math will be like this:
60000 - 12000 = 48000 // deduction
25000 X (10/100) = 2500 // 10% tax on 6500-25000 range
48000 - 25000 = 23000 // first cut 25000
23000 X (15/100) = 3450 // 15% tax on 25000-40000 range
total tax will be 2500 + 3450 = 5950
Code:
<input type=text id="salary">
<div id="total"></div>
<script>
function calc(){
var salary = document.getElementById('salary').value;
var annual = salary * 12;
var net = annual - 12000;
// Define Tax brackets
var bracket1 = (10 / 100);
var bracket2 = (15 / 100);
if (net >= 6500){
if ( net >= 6500 && net <= 25000 ) {
var tax1 = (net * bracket1);
}
else if ( net >= 30000 && net <= 40000 ) {
var tax2 = (net * bracket2);
}
var result = (tax1 + tax2) / 12; //monthly tax
document.getElementById('total').innerHTML = result ;
}
</script>
So output comes as NaN, I am not sure if what I have done so far is the right thing or variables inside statement is the problem here.
The algorithm itself seems to be... buggy (you might want to review
it), but, assuming some things myself, this works. Try running it and
see what you can improve.
<html>
<head>
<title>TAX</title>
</head>
<script type="text/javascript">
function calc(){
var result, tax1 = 0, tax2 = 0;
var salary = document.getElementById('salary').value;
var annual = salary * 12;
var net = annual - 12000;
// Define Tax brackets
var bracket1 = (10 / 100);
var bracket2 = (15 / 100);
if (net >= 6500) {
if (net >= 6500 && net <= 25000) {
tax1 = (net * bracket1);
}
else if (net >= 30000 && net <= 40000) {
tax2 = (net * bracket2);
}
result = (tax1 + tax2) / 12; // monthly tax
}
document.getElementById('total').innerHTML = result;
console.log(result);
}
</script>
<body>
<input type=text id="salary" onblur="calc();" value="0" />
<div id="total"></div>
</body>
</html>
There was a missing };
using var inside the if declarations is not a common practice, so I declared them in a bigger scope (calc() for this matter);
I assumed the line if (net = 30000 && net <= 40000) was about net >= 30000, but... your call;
The way it is now, either tax1 or tax2 will be setted. One of them will be zero. That's because of the if/else statements, they are confusing.
ps.: also, you might wanna use the parseFloat, as stated by some, considering the 'incoming' is not always an integer;
pps: I added a value="" in the input so it is - somewhat - defined at all times.
With the example given, this code might help you get started on the logic.
function calc(){
var salary = document.getElementById('salary').value;
var annual = salary * 12;
var net = annual - 12000;
console.log(salary, annual, net);
// Define Tax brackets
var bracket1 = (0.1);
var bracket2 = (0.15);
var tax1 = 0;
var tax2 = 0;
var runningNet = net;
if (net >= 6500){
if (net >= 25000) {
tax1 = 2500; // 2500 * 0.10, max tax on bracket 1
runningNet = runningNet - 25000;
tax2 = runningNet * bracket2; // whatever is left over * bracket2
}
else {
tax1 = runningNet * bracket1;
}
var result = (parseFloat(tax1) + parseFloat(tax2));
var monthly = result / 12; //monthly tax
document.getElementById('total').innerHTML = result ;
document.getElementById('monthly').innerHTML = monthly ;
}
}
<input type="text" id="salary" />
<button type="button" onclick="calc()">Calculate</button>
<br/>
Total: <div id="total"></div>
Monthly: <div id="monthly"></div>
I'm trying to make a very simple calculator in HTML and javascript
But it still does not work
My question are:
1. How do I get value from a form and set it as a number, not a string?
2. How do I perform quadratic calculation in javascript?
3. How do I update html content with javascript? So whenever I change the value of the input form and press submit, the result will change based on the input that I type, I've tried the document.getElementById("idhere").innerHTML=valuehere; but still does not work.
<script tyle="text/javascript">
function calculateThis(form) {
var userweight=form.weight.value;
var caffeineamount=form.caffein.value;
var caffeinetimes=form.caffeintimes.value;
var totalcaffeine=caffeineamount*caffeinetimes;
// Calculate max caffeine per person
var maxcaffeine=userweight*10;
// Calculate remaining after 24 hours
// Half life = 6 hours
var totalcaffeineafter=totalcaffeine(1/16);
// Calculating how many hours until the caffeine completely digested
var totaldigest=totalcaffeine;
var digesttime=0;
while (totaldigest>0.05) {
totaldigest=totaldigest(1/2);
digesttime++;
}
digesttime=digesttime*6;
// Calculating when the user will probably die of overdose
var countcaffeine=0;
var overdosetime=1;
while (countcaffeine<maxcaffeine){
countcaffeine=countcaffeine+totalcaffeine;
overdosetime++;
}
// Show total amount of caffeine
document.getElementById("showtotalkafein").innerHTML=totalcaffeine;
// Show amount of caffeine after 1 day
document.getElementById("showtotalkafeinsetelah").innerHTML=totalcaffeineafter;
// Show digest time
document.getElementById("showwaktudigest").innerHTML=digesttime;
// Show overdose
document.getElementById("showberapakali").innerHTML=overdosetime;
return false;
}
</script>
<form class="form">
Weight<br />
<input type="text" name="weight" class="required" value="" /><p />
Amount of caffein in coffee<br />
<input type="text" name="caffein" class="required" value="" /><p />
How many times drinking coffee in a day<br />
<input type="text" name="caffeintimes" class="required" value="" /><p />
<button type="button" onclick="calculateThis(this.form); return false;">Calculate</button></form>
<h1>Result</h1>
<p id="showtotalkafein">Show Caffein Total Here</p>
<p id="showtotalkafeinsetelah">Show Caffeine Amount After 24 hours</p>
<p id="showwaktudigest">Show Digest TIme Here</p>
<p id="showberapakali">Show Overdose Time Here</p>
function calculateThis(form) {
var userweight = parseInt(form.weight.value, 10);
var caffeineamount = parseInt(form.caffein.value, 10);
var caffeinetimes = parseInt(form.caffeintimes.value, 10);
var totalcaffeine = caffeineamount * caffeinetimes;
console.log(totalcaffeine)
// Calculate max caffeine per person
var maxcaffeine = userweight * 10;
// Calculate remaining after 24 hours
// Half life = 6 hours
var totalcaffeineafter = totalcaffeine * (1 / 16);
// Calculating how many hours until the caffeine completely digested
var totaldigest = totalcaffeine;
var digesttime = 0;
while (totaldigest > 0.05) {
totaldigest = totaldigest * (1 / 2);
digesttime++;
}
digesttime = digesttime * 6;
// Calculating when the user will probably die of overdose
var countcaffeine = 0;
var overdosetime = 1;
while (countcaffeine < maxcaffeine) {
countcaffeine = countcaffeine + totalcaffeine;
overdosetime++;
}
// Show total amount of caffeine
document.getElementById("showtotalkafein").innerHTML = totalcaffeine;
// Show amount of caffeine after 1 day
document.getElementById("showtotalkafeinsetelah").innerHTML = totalcaffeineafter;
// Show digest time
document.getElementById("showwaktudigest").innerHTML = digesttime;
// Show overdose
document.getElementById("showberapakali").innerHTML = overdosetime;
return false;
}
DEMO
Note
Here I used .parseInt() which used to convert a number to integer, if you need any value in Float then use .parseFloat()`.
Problems in your code
form.weight.value, form.caffein.value ... give value as string, so you need to convert them to number (integer/ float).
you used totalcaffeine(1 / 16) and totaldigest = totaldigest(1 / 2);, not a valid Math operation in javascript, it should be totalcaffeine * (1 / 16) and totaldigest = totaldigest * (1 / 2);
According to your comment
What .parseInt(form.caffeintimes.value, 10), do?
Format of parseInt is:
.parseInt(valueToConvert, [radix]).
So, .parseInt(form.caffeintimes.value, 10) will convert form.caffeintimes.value string to a 10-base integer.
Related refs:
.parseInt()
.parseFloat()