Pages

Donut Manager

A simple JavaScript application to see the language in action. You can have a first approach to constants, variables, conversion from string to integer, the meaning of NaN, and how to specify the number of decimals for a floating point value.

Lot of stuff in a handful of lines.

To define a constant value in JavaScript we use the keyword const, it is costumary to give an all-uppercase name to a constant - C-style tradition.

A variable is introduced by the keyword var, notice that we let JavaScript deduce the type of the variable by the context.

To force the variable value to a specific type we should use standard JavaScript functions. For instance, converting a string to an integer value is done by parseInt().

We we try to get a number from a variable that does not contain such a value, we get a predefined constant, NaN (Not a Number). To check if a variable for NaN we use the isNaN() function.

Given a variable containing a number value, we can use the toFixed() method that we can call on the variable itself.

Let see how to use these concepts in an HTML page:

<html>
<head>
<title>Duncan's Just-In-Time Donuts</title>

<script type="text/javascript">
function update() {
const TAXRATE = 0.0925;
const PRICE = 0.50;

var cDonuts = parseInt(document.getElementById("cdonuts").value);
var gDonuts = parseInt(document.getElementById("gdonuts").value);

// avoid NaN
if(isNaN(cDonuts))
cDonuts = 0;
if(isNaN(gDonuts))
gDonuts = 0;

var subTotal = (cDonuts + gDonuts) * PRICE;
var tax = subTotal * TAXRATE;
var total = subTotal + tax;

document.getElementById("sub").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}

function placeOrder(form) {
// Submit the order to the server
alert("Not implemented yet!");
//form.submit();
}
</script>
</head>

<body>
<h2>Duncan's Just-In-Time Donuts</h2>
<p><i>All donuts 50 cents each, cake or glazed!</i></p>
<form name="orderform" action="donuts.php" method="POST">
<p>Your name: <input type="text" id="name" value="" /></p>
<p>C donuts #:<input type="text" id="cdonuts" onchange="update()" /></p>
<p>G donuts #:<input type="text" id="gdonuts" onchange="update()" /></p>
<p>Ext. pickup: <input type="text" id="pickup" /> minutes</p>
<br />
<p><input type="text" id="sub" readonly="readonly" /> Subtotal</p>
<p><input type="text" id="tax" readonly="readonly" /> Tax</p>
<p><input type="text" id="total" readonly="readonly" /> Total</p>
<p><input type="button" value="Place Order" onclick="placeOrder(this.form);" /></p>
</form>
</body>
</html>


Post written while reading chapter two of Head First JavaScript, a fun book to read.

No comments:

Post a Comment