How to calculate a constant tax rate? - javascript

This is the problem that I need to resolve.
Create a basic webpage that includes an input form. JavaScript is to be embedded into your HTML document.
The input form should include:
Field for user name input
Field for order quantity input
Read only field for item price – set to a value of 5.31
Read only field for order total cost
“submit button” that does NOT use any type of form button element
User should be able to input their name and order quantity, then click “submit”. When “submit” is clicked, form will calculate an order total, including sales tax of 8.25%. Once calculated, the order total form field is to be updated with a total, including dollar sign and two decimal places. An alert box should also be triggered stating the users name and a message indicating the order total including sales tax.
Be SURE to test with your own sample data to verity your calculations are correct.
I did the html and javascript but I can't calculate the const TAXRATE OF 8.25. The Item cost 5.31 and when the tax is included in the total, is huge amount calculated. Thanks for your help in advance. Please check my script here:
<link rel="stylesheet" type="text/css" href="2Examp.css">
<script type="text/javascript">
function calcOrder() {
const TAXRATE = 8.25;
var userName = document.getElementById("username").value;
var quantity = document.getElementById("quantity").value;
var cost = document.getElementById("cost").value;
var extendedCost = quantity * cost;
var taxAmount = extendedCost * TAXRATE;
var orderCost = extendedCost + taxAmount;
document.getElementById("costExtended").value = "$" + orderCost.toFixed(2);
alert("Hello " + userName + " - Your order of " + quantity + " widgets, total $" + orderCost.toFixed(2) + ", including tax.");
}
</script>
</head>
<body>
<h1>Lesson #2 - Sample Page</h1>
<form action="" method="post" enctype="multipart/form-data" name="wigetCalc">
<label for="form-name">Name</label>
<input name="username" id="username" type="text" maxlength="15" /><br />
<label for="form-quantity">Widget order quantity</label>
<input name="quantity" id="quantity" type="text" value="0" maxlength="3" /><br />
<label for="cost">Widget cost</label>
<input name="cost" id="cost" type="text" value="5.31" readonly="readonly" /><br />
<label for="order-total">Order Total</label>
<input name="costExtended" id="costExtended" type="text" readonly="readonly" /><br />
<p onclick="calcOrder();" >Process Order</p>
</form>
</body>
</html>

I believe the issue is that you are multiplying by 8.25 rather than 0.0825.
You could change
const TAXRATE = 8.25;
to
const TAXRATE = 0.0825;
Or do the following:
var taxAmount = extendedCost * (TAXRATE / 100);

I believe the problem is that you have a tax rate of 825%.
Instead of setting TAXRATE to 8.25, set it to 0.0825.
8.25% = 8.25 / 100 = 0.0825

Related

pulling information from multiple calculated fields into a sum to display in a single field

I am trying to get this calculated field to pull from multiple forms (15 to be exact) and display a grand total. As of now I can't get anything to show up in the field box. Any help is greatly appreciated!
<script type="text/javascript">
function update()
{
var form = document.forms[0];
var sum = eval(form.sum.value) + eval(form.sum.value);
form.sum.value = isNaN(sum,'all') ? "" : sum;
}
</script>
<form name="form0" onsubmit="false">
<fieldset>
<legend>Pledge Total (total before tax & shipping)</legend>
<label for="f1">Total ($)</label>
<input id="f2" name="sum" readonly="readonly">
</fieldset>
</form>

How can I dynamically change the price of a Product based on the amount of characters entered into a Custom Field by a Shopper?

I am currently working on a WordPress website, with WooCommerce functionality. On the Product Page, I have created a Custom Field, which allows shoppers to enter a piece of text that they would like to appear on the associated product.
Each product has a starting price with my client wanting to then charge the shopper an additional fee of (for example) £1 per letter entered into the Custom Field.
My client would then like the Product Price, on the Product Page, to change in real time to reflect the amount of letters entered. For example:
Product A: £20
As shopper enters 5 letters, the Product Price changes to £25 in real
time.
So far, I have created the Character Counter on the Product Page, using the following code:
JavaScript/jQuery:
<script type="text/javascript">
jQuery(document).on('keyup', '.product-custom-text', updateCount);
jQuery(document).on('keydown', '.product-custom-text', updateCount);
function updateCount() {
var cs = jQuery(this).val().length;
jQuery('#character_count').text(cs);
}
</script>
At present, I am Outputting this Character Counter through the use of the below code in the functions.php file:
Code Entered into functions.php file:
function custom_character_counter(){
echo 'Letters Entered: <span id="character_count"></span>';
}
add_action('woocommerce_single_product_summary', 'custom_character_counter');
I could be wrong, but I assume I now need to manipulate the product price to reflect the following equation:
Original Product Price + (Characters Entered x £1)
Does anyone have any idea on how I can achieve this or indeed if there is a better approach?
Thanks in advance.
Add an input hidden for the product price / price per letter / and new price then do the computation with it .. the new price will be the one to be pass to the form for its total price.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-letters-container">
<h1>Product 1</h1>
<input type="hidden" name="price" class="product-price" value="20" />
<input type="hidden" name="price" class="letter-price" value="2" />
<input type="text" name="letters" class="product-custom-text" />
<input type="hidden" name="price" class="product-new-price-hidden" />
<div class="character_count"></div>
</div>
<div class="custom-letters-container">
<h1>Product 2</h1>
<input type="hidden" name="price" class="product-price" value="25" />
<input type="hidden" name="price" class="letter-price" value="5" />
<input type="text" name="letters" class="product-custom-text" />
<input type="hidden" name="price" class="product-new-price-hidden" />
<div class="character_count"></div>
</div>
<script type="text/javascript">
jQuery(document).on('keyup', '.product-custom-text', updateCount);
jQuery(document).on('keydown', '.product-custom-text', updateCount);
function updateCount() {
var strlen = jQuery(this).val().length;
var lettertotal = parseInt(jQuery(this).parent().children('.letter-price').val()) * strlen;
var totalprice = parseInt(jQuery(this).parent().children('.product-price').val()) + lettertotal;
jQuery(this).parent().children('.product-new-price-hidden').val(totalprice);
jQuery(this).parent().children('.character_count').text(totalprice);
}
</script>

Keeping a running total with Javascript in a span element

I'm trying to write a piece of code that is supposed to keep a running total. More specifically what I would like it to do is, every time you click the button to add the sub total to the total, it should keep adding into the subtotal. The way the whole thing works now is, there is three meal items to choose from in a dropdown that each have their own price. When a food item is selected, the user types in how many of that item they want. Then user clicks the add to total button to add the food item to one text field. Under that field is a span that shows the grand total after a $3.50 delivery charge is added on. The span is where I want the running total to keep adding the sum every time the button is clicked. I am new to Javascript so I've been trying my best. I've also looked at topics here on SO to see if I can find something similar to my issue and I've seen some that are close but not quite what I'm looking for. Here"s my code...
<script>
function myTotal()
{
var meals = document.getElementById("foodItems").value;
var howMany = document.getElementById("itemTotal").value;
var shippingCost = "3.50";
var totalBill = parseFloat(meals) * howMany + parseFloat(shippingCost);
var addingTotal = parseFloat(meals) * howMany;
var runTotal = document.getElementById("runningTotal").value;
if (isNaN(totalBill)) { // Cash calculator
document.getElementById("total").value = "Invalid amount"
//alert("result of isNaN" ); //The input amount is a non numeric string. It is or contains letters and/or spaces
}
else { //adds total to the sub total field
document.getElementById("total").value = "$" + parseFloat(addingTotal).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//Convert input value into a floating point number. toFixed() requires a number value to work with
}//end Cash Calculator
var i = ""; //This piece is where I'm trying to begin the running total
if(i=totalBill, i=howMany*totalBill, i++ ){//adds delivery charge + subtotal. But doesn't keep a running total
document.getElementById("runningTotal").innerHTML = parseFloat(totalBill).toFixed(2);
}
else {
document.getElementById("runningTotal").innerHTML = parseFloat(i++) * howMany;
}
}
</script>
<form id="survey" name="survey" method="get" action="formHandler.php" class="col-4">
<!-- enter your forms code below -->
<div id="fieldset">
<legend>Place an Order!</legend>
<h3>There is a $3.50 delivery fee</h3>
<fieldset>
<label for="foodItems">Quick Meal Food Items</label>
<select name="foodItems" id="foodItems">
<option value="6.00">Pepperoni Pizza - $6.00</option>
<option value="3.00">Bacon BBQ Burger - $3.00</option>
<option value="8.00">Steak and Eggs - $8.00</option>
</fieldset>
<!--The "input" element has "required" in the parameters so the user must fill out all fields but the email.-->
<fieldset>
<input type="text" name="itemTotal" id="itemTotal" size="25" required>How Many Orders?(Limit To 5 per Meal Type)</input>
</fieldset>
<fieldset>
<input type="button" name="click" id="button" value="Add to Order" onClick="myTotal()">
<input type="text" name="total" id="total" size="25">Grand Total</input>
<br>
<span id="runningTotal"></span> <!--runningTotal span-->
</fieldset>
<label for="name">Name: (First, Last)</label>
<input type="text" name="name" id="name" size="25" required></input>
<label for="Address">Address</label>
<input type="text" name="Address" id="address" size="25" required></input>
<label for="email">Email</label>
<input type="email" name="email" id="email" size="40" maxlength="40"></input>
<br><br>
<label for="checkbox">Sign me up for deals via email</label>
<input type="checkbox" name="checkbox" id="checkbox" value="Signup" checked="checked"></input>
<input type="submit" method="post" value="Submit" class="button"/>
<input type="reset" value="Reset" class="button"/>
</form>
</div>
Any help would be awesome! Please address any confusion please. I want to be as clear as possible to try to get the best help for me and others here on SO. I also hope my question isn't off topic. Like I said, I tried to find something pertaining to this here on SO. Thank you so much!
Do you mean something like this? (jsfiddle here)
function myTotal()
{
// Error checking removed....
// Calculate cost of current item
var itemSelect = document.getElementById("foodItems");
var mealCost = parseFloat(itemSelect.value);
var howMany = parseInt(document.getElementById("itemTotal").value);
var thisItemCost = mealCost * howMany;
var shippingCost = 3.5;
// Get running total from the "total" text box
var runTotal = parseFloat(document.getElementById("total").value);
// Only add shipping cost once
if (isNaN(runTotal) || 0 == runTotal) runTotal = shippingCost;
// Add this item to total and update "total" text box
document.getElementById("total").value = (thisItemCost + runTotal).toFixed(2);
// Add item to span
document.getElementById("runningTotal").innerHTML += "</br>" +
itemSelect.options[itemSelect.selectedIndex].innerHTML +
" x " + howMany +
" .... $" + thisItemCost.toFixed(2);
}

How to populate a form box with javascript based on other form box inputs

I have a form with four number inputs: hourly wage, hours worked, number of weeks, and salary.
I want to automatically fill-in the salary box based on the inputs from wage, hours, and weeks boxes.
So in theory, if hourly wage = 15, hours worked = 40, and number of weeks = 52 then the salary form box should automatically be set to "31200"
Any simple way to do this with javascript? I have tried a few different methods and can't seem to get it to work.
If it helps, I have already set all the form boxes to variables:
var wageBox = document.forms[0].wage;
var hoursBox = document.forms[0].hours;
var weeksBox = document.forms[0].weeks;
var salaryBox = document.forms[0].salary;
Edit: sorry, here's the HTML form code:
<fieldset id="incomeinfo">
<label for="wage">
Hourly wage:
<input type="number" id="wage" name="wage" placeholder="e.g. 15.00">
</label>
<label for="Hours">
Hours worked each week:
<input type="number" id="hours" name="hours" value="40" placeholder="e.g. 40">
</label>
<label for="Weeks">
Number of weeks a year:
<input type="number" id="weeks" name="weeks" value="52" placeholder="e.g. 52">
</label>
<br />
<br />
<label for="salary">
Salary:
<input type="number" id="salary" name="salary" placeholder="e.g. 31200" required>
</label>
</fieldset>
You can add a event for when the inputs change and calculate the salary based off of their values. Quick mock up.
Fiddle: http://jsfiddle.net/AtheistP3ace/6uatoyd2/
JS:
function calculateSalary () {
// Get all values we need to calculate
var wage = parseInt(document.getElementById('wage').value, 10);
var hours = parseInt(document.getElementById('hours').value, 10);
var weeks = parseInt(document.getElementById('weeks').value, 10);
// Calculate salary
var salary = wage * hours * weeks;
// Only update salary if we got number
if (!isNaN(salary)) {
document.getElementById('salary').value = salary;
}
}
// Get all inputs, loop and attach change event with calculateSalary handler
var inputs = document.getElementsByTagName('input');
var index = 0, length = inputs.length
for ( ; index < length; index++) {
inputs[index].addEventListener('change', calculateSalary);
}
HTML:
<input type="text" id="wage" placeholder="wage" />
<input type="text" id="hours" placeholder="hours" />
<input type="text" id="weeks" placeholder="weeks" />
<input type="text" id="salary" placeholder="salary" />
EDIT: Updated fiddle using your HTML. Same code works.
http://jsfiddle.net/AtheistP3ace/6uatoyd2/1/

How to display a variable as a total in an INPUT FIELD instead of a SPAN?

I am having difficult displaying the contents of a variable in a total input field. Basically this code is functioning which is great:
<script>
$(function() {
$('#product-unit-val, #total-unit-sales, #number-reps').change(function() {
var total = parseInt($("#product-unit-val").val()) *
parseInt($("#total-unit-sales").val()) *
parseInt($("#number-reps").val());
if (!isNaN(total)) {
$("#sales-val").html(total);
}
});
});
</script>
Average product unit value <input type="text" id="product-unit-val" /><br/>
Total unit sales value <input type="text" id="total-unit-sales" /><br/>
Number of reps <input type="text" id="number-reps" /><br/>
Total sales value <span id="sales-val"></span>$​​​
However I want to display the total value in an input field like:
<script>
$(function() {
$('#product-unit-val, #total-unit-sales, #number-reps').change(function() {
var total = parseInt($("#product-unit-val").val()) *
parseInt($("#total-unit-sales").val()) *
parseInt($("#number-reps").val());
if (!isNaN(total)) {
$("#sales-val").html(total);
}
});
});
</script>
Average product unit value <input type="text" id="product-unit-val" /><br/>
Total unit sales value <input type="text" id="total-unit-sales" /><br/>
Number of reps <input type="text" id="number-reps" /><br/>
Total sales value <input type ="text" id="sales-val"/>​
Am I missing the obvious? I just can't seem to get this working.
Many Thanks
Use val to change the value of an input :
$("#sales-val").val(total);
But be careful with parseInt, always specify the radix :
parseInt('09') == 0
parseInt('09', 10) == 9

Categories