Javascript/Ajax/Jquery Dynamically calculate form on change - javascript

I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based on the other ones.
Example:
Total Parts (Mysql)
Labor (User)
Misc (User)
Sub Total (Dynamic total of above)
Tax (Dynamic calc of above - sub * 13%)
Total (Sub + Tax)
I have searched around but can not quite find what I am looking for, and my skills are zero in Javascript/Ajax/Jquery so I haven't been able to modify anything to work, although I have tried miserably.
Can someone help me out on this or point me to a script that may suit my needs.
Thanks

Alright sorry, I thought you were looking for some complex code. Here is a simple example of exactly what you're looking for.
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
Obviously this doesn't grab the dynamic value from a database. If you use PHP you can swap this line:
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
for one like this:
<div>Total Parts: <input type="text" id="parts_input" value="<?PHP include('getTotalParts.php'); ?>" readonly="true" /></div>
Where the getTotalParts.php is a file you make to get your database information. It can simply grab the information and do a "echo $totalParts;"

You can just use onblur (activated when a user leaves each of the input fields) to calcuate the fields.
...<input name="labour" id=total onblur="$('#total').val($('#sub').val() + $('#tax').va())">
You haven't provided enough information to comment on the "Total Parts" field.

Related

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;
}

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

Calculating taxes based on income and wealth input in HTML form

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/

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