function updatesub(){
var u = parseInt(document.getElementById(unitcost).value, 10);
var q = parseInt(document.getElementById(quantity).value, 10);
subtotal = u*q;
document.getElementById("sub").value=subtotal;
}
FYI, your original u and q were completely wrong. They were missing the var statement.
<script type="text/javascript" >
function updatesub(){
var u = parseInt(document.getElementById(unitcost).value);
var q = parseInt(document.getElementById(quantity).value);
var subtotal = u*q;
document.getElementById("sub").value=subtotal;
}
</script>
As a warning to others though, jslint.com advertises that it will make you cry.
It’s a harsh mistress, but with good reason.
As an example, when “The Good Parts” is clicked, and you select “assume a web browser”, here is what jslint.com has to say about the following script from earlier:
function updatesub(){
var u = parseInt(document.getElementById(unitcost).value);
var q = parseInt(document.getElementById(quantity).value);
var subtotal = u*q;
document.getElementById("sub").value=subtotal;
}
is reported to have 15 problems.
“use strict”; allows Strict Mode for your code, which provides extra protections. Here’s some info from John Resig about strict mode.
Placing a space between the parenthesis and the curly brace is one of a standard set of code conventions that aid and enhance readability of the code.
Indent the function code by four spaces, a code convention for readability. I adjusted the tab to be 4 spaces as well.
unitcost is not defined, it should be text instead, as is quantity
Missing radix parameter, which for parseInt means to specify a second parameter of 10, which means to default to decimal values.
Too many var statements. It used to be a convention to use multiple var statements at the top of the code, but it’s not recommended to use a sigle var statement.
space-separate operators such as * and =
which results in the following code that jslint.com is now completely happy with.
"use strict";
function updatesub() {
var u = parseInt(document.getElementById('unitcost').value, 10),
q = parseInt(document.getElementById('quantity').value, 10),
subtotal = u * q;
document.getElementById("sub").value = subtotal;
}
which isn’t quite what jslint expected though. What it is expecting you to do is
function updatesub() {
var u, q, subtotal;
u = parseInt(document.getElementById('unitcost').value, 10);
q = parseInt(document.getElementById('quantity').value, 10),
subtotal = u * q;
document.getElementById("sub").value = subtotal;
}
placing commas between the statements will break the code if you forget why they are there and either delete them or replace them with semicolons. The idea iis to define all of the local variables at the top regardless of where in the script you actually use it since JavaScript is going to work on the assumption that your code does this anyway.