Calculating taxes based on income and wealth input in HTML form - javascript

I have a form where the user can type his income and savings. I want to calculate taxes based on that info and display it on the screen when i click a button. I'm trying to do this using JavaScript, which i'm very new to. Also pretty new to HTML forms.
Here's the pseudocode for the tax calculation itself:
tax(income, wealth) = (0.35 * income) + (0.25 * wealth)
Here's my attempt on making a this work. I didn't include all the HTML code here, only the last part of the form.
HTML
<form>
<label>Income</label>
<input id="income" type="number" name="income" min="0"><br>
<label>Wealth</label>
<input id="wealth" type="number" name="wealth" min="0"><br>
<label>Tax</label><br>
<input id="tax" type="number" name="tax" disabled>
<button type="button" name="button" onclick="calculatetax();"> Calculate
tax</button>
</form>
<script type="text/javascript" src="script.js"> </script>
Javascript
function calculatetax() {
var salary = document.getElementById('income').value;
var savings = document.getElementById('wealth').value;
var taxes = (0.35 * salary) + (0.25 * savings);
var totalTax = document.getElementById('tax')
totalTax.innerHTML = taxes.value;
}
I want to make the tax result appear on the screen when i click the button, and i want it to appear in the "tax" input if that makes sense.

Personally I'd set your disabled tax input to readonly. It allows the user to still copy the value unlike your disabled input.
This:
<button type="button" name="button" onclick="calculatetax();"> Calculate
tax</button>
Can be changed to:
<button type="button" name="button" onclick="calculatetax()"> Calculate
tax</button>
You are assigning our JavaScript variable taxes to a value. You don't need to get the value with .value instead just do:
totalTax.innerHTML = taxes;

There is a problem with your JS
var totalTax = document.getElementById('tax')
totalTax.innerHTML = taxes;
taxes is just a variable, it does not have an attribute of value
Demo: https://liveweave.com/6X4DKW
https://jsfiddle.net/r1xsv9dm/

Related

Have the cart update with price, and then offer a coupon if subTotal is over $40

Working on a school assessment testing basic HTML design. I want to add a function that when you submit a quantity it will update the cart subtotal, and if that subtotal is larger than 40 it will give an alert signifying a discount code. I am new to javascript and coding in general so am struggling big time. I feel like I am so close but getting 'NaN' which I assume is because the id=quantity is not being fed into the function.
For the purposes of the assignment I would like to not use jquery, and php is not necessary.
relevant html:
<div id="quantity">
<h4>How many people are coming?</h4>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" pattern="[0-9]+" onchange="cartUpdate()" >
</div>
<div id="cart">
<p>Total Cost: <span id="subTotal"></span></p>
<button id="submit" type="submit" value="Order">Submit Order</button>
</div>
javascript:
var quantity = document.getElementById("quantity").value;
function cartUpdate() {
var subTotal = (15 * quantity).toFixed(2) - 0 ;
document.getElementById("subTotal").innerHTML = "$" + subTotal;
}
document.getElementById("submit").addEventListener("click", function() {
if (subTotal > 40) {
alert("Your ticket has been sent to your email. Since you have spent over $40, you are also eligible for a 20% off coupon for the snack bar which is included in your ticket.")
}});
It is giving you NaN instead of total because you have stored the value of quantity on a page load which is undefined at program start. To fix this get the latest value everytime value changes. See the code below it works as you expected.
var quantity = document.getElementById("quantity").value;
var subTotal = 0;
function cartUpdate(e) {
subTotal = (15 * e.target.value).toFixed(2) - 0;
document.getElementById("subTotal").innerHTML = "$" + subTotal;
}
document.getElementById("submit").addEventListener("click", function() {
if (subTotal > 40) {
alert(
"Your ticket has been sent to your email. Since you have spent over $40, you are also eligible for a 20% off coupon for the snack bar which is included in your ticket."
);
}
});
<div id="quantity">
<h4>How many people are coming?</h4>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" pattern="[0-9]+" onchange="cartUpdate(event)" />
</div>
<div id="cart">
<p>Total Cost: <span id="subTotal"></span></p>
<button id="submit" type="submit" value="Order">Submit Order</button>
</div>

How can I add HTML values via JavaScript and output the result? [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I have some simple multiplication and addition that I'm performing via JavaScript and outputting the result into an HTML Element on a webpage. For some reason the output seems to be a combonation of two values rather that a SUM value. I've attached a screenshot of my results.
function ccFeeCalculation(){
var payment = document.getElementById('payment_amount').value;
var fee = .03 ;
var feeAmount = (payment * fee)*1.00;
var paymentPlusFee = payment + feeAmount;
console.log("fee amount:" + paymentPlusFee);
document.getElementById("processingFee").textContent = feeAmount;
document.getElementById("processedAmount").textContent = paymentPlusFee;
}
<h2><label>Step1: Payment Amount:</label>
<input class="currencyTextBox" type="text" name="payment_amount" id="payment_amount" size="6" onKeyUp="ccFeeCalculation();" /></h3>
This amount can be changed in order to make a partial payment.<br /><br />
<div id="ccFee" style="display: none">
<font color="red"><span id="feePercentage">A 3% Fee Will Be Applied:</span> <span id="processingFee" class="currencyTextBox"></span><br>
Amount to be processed today: <span id="processedAmount" class="currencyTextBox"></span><br><br>
</font>
</div>
If my payment amount is typed as 10.00, it shows the correct fee amount of .30 but when it added the two values, the result is 10.000.3
I'm sure I'm missing something silly. Can someone shed some light?
It concats the value as the . value returns a string there is a trick to convert string to number just add + sign before variable name and it will get converted to a number.
Do something like this
let payment = +document.getElementById('payment_amount').value;
Parse the value using parseInt():
function ccFeeCalculation() {
var payment = parseInt(document.getElementById('payment_amount').value);
var fee = .03;
var feeAmount = (payment * fee) * 1.00;
var paymentPlusFee = payment + feeAmount;
console.log("fee amount:" + paymentPlusFee);
document.getElementById("processingFee").textContent = feeAmount;
document.getElementById("processedAmount").textContent = paymentPlusFee;
}
<h2>
<label>Step1: Payment Amount:</label>
<input class="currencyTextBox" type="text" name="payment_amount" id="payment_amount" size="6" onKeyUp="ccFeeCalculation();" /></h3>
This amount can be changed in order to make a partial payment.<br /><br />
<div id="ccFee">
<font color="red"><span id="feePercentage">A 3% Fee Will Be Applied:</span> <span id="processingFee" class="currencyTextBox"></span><br> Amount to be processed today: <span id="processedAmount" class="currencyTextBox"></span><br><br>
</font>
</div>
A little bit of improved markup .. I think when you are going to sum up the final then sum it after the form is ready to submit with all validations not when the person is just vaguely writing any values inside the input ! .. Also corrected the js..
The problem was simple you needed to extract the interger value from the input so use parseInt(Val) method ( or parseFloat ) .
Check it out =>
HTML
<form id="form" action="" method="get" accept-charset="utf-8">
<label for="payment_amount">
<h2> Step1: Payment Amount:</h2>
</label>
<input class="currencyTextBox" type="text" name="payment_amount" id="payment_amount" size="6" />
<button>Submit</button>
</form>
<p>
This amount can be changed in order to make a partial payment.
</p>
<br /><br />
<div id="ccFee" style="display: none">
<font color="red"><span id="feePercentage">A 3% Fee Will Be Applied:</span> <span id="processingFee" class="currencyTextBox"></span><br>
Amount to be processed today: <span id="processedAmount" class="currencyTextBox"></span><br><br>
</font>
</div>
JS
const form = document.querySelector('#form');
form.onsubmit = function (e) {
e.preventDefault();
let payment = document.getElementById('payment_amount').value;
payment = parseInt(payment) // parseFloat incase float value
const fee = 0.03;
const feeAmount = (payment * fee) * 1.00;
const paymentPlusFee = payment + feeAmount;
console.log("fee amount:" + paymentPlusFee);
document.getElementById("processingFee").textContent = feeAmount;
document.getElementById("processedAmount").textContent = paymentPlusFee;
}

Trying to run a program that calculates the needed grade on a final exam to get their desired overall grade

I am trying to run a program that allows a user to input their current overall grade grade (f), their desired overall grade (dg), and the weight of their final exam (g), and would ideally return their needed grade on the final exam to achieve their desired grade.
I have the equation, but am not sure why it is not returning a result on the screen. Can anyone tell me why?
<!DOCTYPE html>
<html>
<title>ffdfsdfdsfdsf</title>
<head>
<script>
function blahBlah
() {
var f = document.getElementById ('f').value
var f = document.getElementById ('f').value
var f = document.getElementById ('f').value
var f = (f - f *(4 - f)) / f
}
</script>
</head>
<h1>
f</h1>
<body>
<p>fe: <input id="cg" min="1" max="120"
onchange="blahBlah"</p>
<p>f: <input id="dg" min="3" max="11"
onchange="cf"</p>
<p>f: <input id="wof" min="3" max="11"
onchange="f"</p>
<p><button>Submit</button></p>
<h2 id="f"></h2>
</body>
</html>
Like I said, ideally there are three forms. Once the user completes these inputs, a pop up of their needed grade on the final would pop up under the submit button.
You had some syntax errors which I have corrected in this snippet, namely you needed to make it a string when you were setting innerHTML (thought you should probably use innerText), your <input> tags weren't closed, and you need to invoke your function with () in your onchange attributes.
function computeGrade() {
var cg = document.getElementById("cg").value;
var dg = document.getElementById("dg").value;
var wof = document.getElementById("wof").value;
var ng = (dg - cg * (100 % -wof)) / wof;
document.getElementById("ng").innerHTML = "Needed_grade: " + ng + "%";
}
<h1> Class Calculator</h1>
<p>Current grade: <input id="cg" min="1" max="120"
onchange="computeGrade()"></input></p>
<p>Desired grade: <input id="dg" min="1" max="120"
onchange="computeGrade()"></input></p>
<p>Final weight: <input id="wof" min="1" max="100"
onchange="computeGrade()"</input></p>
<p><button>Submit</button></p>
<h2 id="ng"></h2>

Trying to calculate the total price of items taking into account the quantity selected Javascript

this is my first time posting on this site. i have a webpage that outlines one of my products that I intent to sell
here is my dilemma. I have this code that asks the user to press + and - buttons for the quantity of the item that they want. Now what i am trying to work out is if the user presses + or - any number of times I need to be able to to take into account the number of clicks and calculate the total price for the order on a separate line. Im very new to javascript all help is appreciated thanks
<form>
<br> Item Price: $463.50
<br> Please Select Quantity
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
<input type='button' name='add' onclick='javascript: document.getElementById("qty").value++;' value='+'/>
<input type='text' name='qty' id='qty' />
</form>
<form>
<br> Item Price: $<span id='price'>463.50</span>
var unitprice = (document.getElementById('price').innerText || document.getElementById('price').textContent);
var price = parseFloat(unitprice);
var count = parseInt(document.getElementById("qty").value, 10)
var total = price * count;
alert(total); // or do whatever you want
I would separate out the Javascript code into its own <script> element, and do something like:
<form>
<br/> Item Price: $<span id="price">463.50</span>
<br/> Please Select Quantity
<input type="button" name="subtract" id="subtract" value="-"></input>
<input type="button" name="add" id="add" value="+"></input>
<input type="text" name="qty" id="qty" value="0"></input>
<br/> Total
<input type="text" name="total" id="total" value="0"></input>
</form>
The Javascript would look like:
$(function() {
var price = parseFloat($('#price').text());
$('#subtract').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
if ( current > 0 ) {
$qty.val(current-1);
$('#total').val(price*(current-1));
} else {
$('#total').val(0);
}
});
$('#add').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
$qty.val(current+1);
$('#total').val(price*(current+1));
});
});
You can see it in action.
This is all do-able without jQuery, but it makes life a lot easier!
Since you mentioned you're new to this, a word of WARNING: In the real app only use the quantity from the page, and re-calculate out how much to charge them on the back end. It would be very easy for someone to modify either the price or total in the DOM; if you were to use the price or total from the DOM then a malicious user could buy it for any price they wanted! Always assume input is malicious or incorrect.
var value = parseInt(document.getElementById("qty").value, 10)
item_price = item_price * value;
document.getElementById("someid").innertHTML = item_price;

Dynamically Update fields through Input field and dropdown

I'm trying to dynamically update a text field through an input field. This will then be linked to a dropdown selection with values. I also need to show a due date to show 30 days in advance from today's date.
Here is my HTML:
<div>
<label for="payment">Payment:</label>
<input type="text" name="amount" id="amount" onChange="myfunction()"/>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1">Fast</option>
<option value="2">Medium</option>
<option value="3">Slow</option>
</select>
</div>
<br />
<div>
Payment Breakdown: <br /><br />
Payment:
<div name="amount" id="amount"></div>
Freight:
<div name="delivery" id="delivery"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
</div>
I'm struggling with the Javascript part though and fitting it all together.
I've gotten as far as this and now I'm stuck. (Not very far I know)
function myFunction()
{
var amount = document.getElementById("amount");
var delivery = parseInt($(this).find("option:selected").val());
total = amount + delivery
$("#total").html(total);
};
I've looked at examples on Stackoverflow and Google but nothing seems similar to what I'm trying to achieve. Although I know the answer is out there, I'm not sure if I'm asking the right question.
Cheers
I would change it to this. Here I have an updateCost() function which is called when the amount is changed or the delivery is changed. I also added code to handle the due date.
Remove the inline onchange event from the amount:
<input type="text" name="amount" id="amount"/>
Javascript:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = amount + delivery
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
// handle the due date
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30);
var dateStr = todayPlus30.getDate() + "/" + (todayPlus30.getMonth()+1) + "/" + todayPlus30.getFullYear();
$('#date').html(dateStr);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
Your original code has a few problems:
The wrong case on the inline function call
The use of this within the function when this is not actually any of your elements (you didn't pass it as an argument).
The use of amount in the calculation when amount is an input element, not a value.
From a usability point of view, it would only try to update when the amount is changed, I think it would be better to update on both change of the amount and delivery.

Categories