I am creating a calculator and I have written the following code:
For javascript:
function calculate() {
'use strict';
var total;
var quantity = document.getElementById('quantity').value;
var price = document.getElementById('price').value;
var tax = document.getElementById('tax').value;
var discount = document.getElementById('discount').value;
total = quantity*price;
tax /= 100;
tax++;
total *= tax;
tax = tax/100;
tax = tax+1;
total = total*tax;
total -= discount;
document.getElementById('total').value = total;
return false;
}
function init() {
'use strict';
var theForm = document.getElementById('theForm');
theForm.onsubmit = calculate;
}
window.onload=init;
For html:
<div><label for="quantity">Quantity</label><input type="number"
name="quantity" id="quantity" value="1" min="1" required></div>
<div><label for="price">Price Per Unit</label><input type="text"
name="price" id="tax" value="1.00" required></div>
<div><label for="tax">Tax Rate (%)</label><input type="text"
name="tax" id="tax" value="0.0" required></div>
<div><label for ="discount">Discount</label><input type="text"
name="discount" id="discount" value="0.00" required></div>
<div><label for="total">Total</label><input type="text" name="total"
id="total" value="0.00"></div>
<div><input type="submit" value="Calculate" id="submit"></div>
I have saved the files respectively as shopping.js and shopping.html but I don't know how to interconnect the code together so that when I click on the shopping.html and the browser opens, the calculator works properly.
I have tried to include the javascript code in the html code by using the script tags but it didn't work. I read some articles that said you have to save them in the same directory, but I did not understand that. I saved them on my desktop in a file called shopping and I need some assistance from here.
Thank you.
Check here
The id for price was "tax" I think was just typo mistake. I changed also your input type sumbit to a button instead.
Code:
window.onload = function() { // this loads your script when the page loads
function calculate() {
'use strict';
var total = 0;
var quantity = document.getElementById('quantity').value;
var price = document.getElementById('price').value;
var tax = document.getElementById('tax').value;
var discount = document.getElementById('discount').value;
total = quantity * price;
tax /= 100;
tax++;
total *= tax;
tax = tax / 100;
tax = tax + 1;
total = total * tax;
total -= discount;
document.getElementById('total').value = total;
return false;
}
};
You can add this code to your page or call it by a external file, then you just need to put this in your html code <script src="shopping.js" type="text/javascript"></script>. Put inside the <head> or <body> tags.
If they're in the same directory, you can call the js file in your HTML page like so:
<script src="shopping.js" type="text/javascript"></script>
If it's in a folder you have to reflect that in the src line: foldername/filename
That's how to get an external js file into your HTML doc. However, if you're putting your js code directly into script tags on the HTML doc and it's still not working, then there's an issue with the code.
Related
I know this question is asking previously but i don't get any solution from that.
I have grid-view and i want to calculate total amount and assign it in another textbox in same row. calculation is working perfect but i am unable to assign output value to next TextBox Tol_Txt.
This is my JavaScript code:
<script type="text/javascript">
function CalculateTotal() {
var grid = document.getElementById("<%= Grid_Delivery_Record.ClientID%>");
for (var i = 0; i < grid.rows.length - 1; i++) {
var rate = $("input[id*=Qty_Txt]");
var qty = $("input[id*=Rate_Txt]");
var totalamount = rate[i].value * qty[i].value; //--- Calculate totalamount fine
$("input[id*=Tol_Txt]") = totalamount[i].value; //--- Unable to assign totalamount in Gridview TextBox
document.getElementById("Tol_Txt").value = totalamount; //--also tried this
document.getElementById("Tol_Txt").innerHTML= totalamount; //--also tried this
}
}
</script>
This is my HTML code:
<td>
<input name="ctl00$cphpagebody$Grid_Delivery_Record$ctl02$Qty_Txt" type="text" id="cphpagebody_Grid_Delivery_Record_Qty_Txt_0" OnKeyUp="CalculateTotal();" placeholder="Qty...." style="font-size:Small;" />
</td><td>
<input name="ctl00$cphpagebody$Grid_Delivery_Record$ctl02$Rate_Txt" type="text" id="cphpagebody_Grid_Delivery_Record_Rate_Txt_0" OnKeyUp="CalculateTotal()" placeholder="Rate...." style="font-size:Small;" />
</td><td>
<input name="ctl00$cphpagebody$Grid_Delivery_Record$ctl02$Tol_Txt" type="text" id="cphpagebody_Grid_Delivery_Record_Tol_Txt_0" style="font-size:Small;" />
</td>
Thanks in advance.
I have searched through all of SOF and couldn't find any topic that matches my problem.
I have written an HTML form that I will use PHP to process later, but I have some options in the form that a user can choose. Here is the HTML code
<label for="FIELD6">Model Type: </label><br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model" checked onclick="doMath()" />Normal Model<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath()" data-clicked="no" />Workshop Model
<p id="total"></p>
So the user can choose between a Normal and Workshop Model. I am trying to set it so that when the user checks the workshopmodel radio button, it adds to the total price (specified in paragraph tags). Here is my attempt at my barely-known language, jQuery:
function doMath() {
var basePrice = 15;
var baseModel = 0;
var customModel = 5;
var modelTotal = ;
function workshopModel() {
if(getElementById("workshopmodel").click(function() {
modelTotal = basePrice + customModel;
}
}
function defaultModel() {
if(getElementById("basemodel").click(function() {
modelTotal = total basePrice + baseModel;
}
}
}
$("#total").html('<font color="black">Total Price:</font><font color="#09ff00">' + workshopModel() + '');
So I am trying to make it add to the basePrice in real time, and then print it in place of the ID marked "total" every time the user makes a change in selection (in real-time). So if the user chooses workshopmodel, the script will add 15 and 5, resulting in 20, and if they choose basemodel, the script will add 15 and 0, resulting in 15. I left the variable modelTotal undefined as it should be defined later on in the script. Can anyone help me out with this?
This should work how you want. Also, does not require jQuery.
function doMath() {
var basePrice = 15;
var baseModel = 0;
var customModel = 5;
var modelTotal;
if (document.querySelector('input[name="FIELD6"]:checked').value == "Normal Model") {
modelTotal = basePrice + customModel;
}
if (document.querySelector('input[name="FIELD6"]:checked').value == "Workshop Model") {
modelTotal = basePrice + baseModel;
}
console.log(modelTotal);
document.getElementById('total').innerHTML = '<span style="color:black">Total Price:' + modelTotal + '</span>';
}
<label for="FIELD6">Model Type:</label>
<br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model" onclick="doMath()" />Normal Model
<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath()" />Workshop Model
<div id="total"></div>
Here is a working example of what I think you are asking for.
<label for="FIELD6">Model Type:</label><br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model" checked onclick="doMath(this)" />Normal Model<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath(this)" data-clicked="no" />Workshop Model
<p id="total"></p>
<script type="text/javascript">
function doMath(ele) {
var total = 15;
if($(ele).attr('id') === 'workshopmodel') {
total += 5;
}
$("#total").html('<font color="black">Total Price:</font><font color="#09ff00">' + total);
}
</script>
New to javascript. Would very much like to produce a simple calculator that uses three inputs and 4 fixed values to produce and report a 'peak power output' value. Code is as follows:
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
html:
<td>
<input id="vj" type="text" oninput="calculate()" />
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" />
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" />
</td>
have this in a html page with table to display input and results, input works, but not results.
You have jquery tagged, so here is a jQuery version.
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = $('#vj').val();
hgt = $('#hgt').val();
wgt = $('#wgt').val();
result = $('#peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.val(peakresult);
}
$(document).ready(function() {
$('input[type="text"]').on('blur', function() {
calculate();
});
});
</script>
This assumes you also have <input type="text" id="peakresult" /> in your HTML.
I added a jQuery event handler that will call the calculate button when the user leaves the input field. That could be more useful than having a handler in the field tag.
if you replace
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
by
vj = Number(document.getElementById('vjump').value);
hgt = Number(document.getElementById('height').value);
wgt = Number(document.getElementById('weight').value);
It should work.
BUT WITH NO check for correct input.
(EDITED)
This following code is working (Tested on Chrome)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = Number(document.getElementById('vj').value);
hgt = Number(document.getElementById('hgt').value);
wgt = Number(document.getElementById('wgt').value);
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
</head>
<body>
<td>
<input id="vj" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="peakresult" type="text" value="0"/>
</td>
</body>
You can use unary plus, +, to turn your values into a number and then perform operations on them:
function add() {
var a = +document.getElementById('firstOperand').value;
var b = +document.getElementById('secondOperand').value;
return a + b;
}
Also your html suggests you are invoking the calculate function every keystroke by using oninput. You can use onblur to call the calculate function after the user leaves the field.
You might need parse text into integer
parseInt(val);
Check this live sample
http://jsfiddle.net/VdrWL/2/
Hope it helps.
This is my function
function doMath() {
var counter; var nvalue; var amount;
var price=100;
nValue = document.getElementById("message").value;
amount=(nvalue*price);
document.getElementById("total").value=amount ;
}
My html
<input type="" name="message" id="message" onkeyup="doMath()"maxlength="60">message
<input type="text" name="total" id="total" maxlength="60"> amount
when user enter value into message field it should calculate the amount automatically and show it in amount field.
but while i entering the value it show NAN
its not calculating can anyone help me how to fix this .i m new to javascript
You declared your variable as nvalue but used nValue instead.
function doMath() {
var nValue; var amount;
var price=100;
nValue = document.getElementById("message").value;
amount=(nValue*price);
document.getElementById("total").value=amount ;
}
Your error is here:
amount = (nvalue * price);
It should be:
amount = (nValue * price);
I have 2 files, my index and my JS file.
In my index I will have a form of input fields and my index file will be linked to my JS file.
In my JS file I will have a list of variables which will get their values from my index file input fields. I plan on then multiplying some of my values together in a function.
What is the correct way of doing this without returning NaN or undefined?
I've been trying to do by setting var values onkeyup or onclick as 'document.getelementbyid' only it never returns anything...
Some sample code would be,
HTML
<input type="radio" id="ServiceLevel" value="0.84" name="ServiceLevel"onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.67" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.56" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.28" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.14" name="ServiceLevel" onclick="getValue()"/>
and JS
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed(2));
}
You need to get the values in the javascript. Here is how you should do
Create a file index.htm
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>
script.js
function Calculate()
{
var v1 = document.getElementById ("a1").value;
var v2 = document.getElementById ("a2").value;
var v3 = document.getElementById ("a3").value;
var total = GetNumeric (v1) + GetNumeric(v2) + GetNumeric(v3);
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
first thing is
var ServiceLevel = document.getElementById(ServiceLevel).value;
// ServiceLevel = null
this should be in function else while opening this web page getElementById will give null.
2
. your input radio button has same name & ID if this is the case which value should be taken OR they are Individual OR Group
I tried this check:
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));
}