///////////////////////////////////////////=================
// Demo of JavaScript by implementing a simple calculator;
// see calculator.html in this same directory.
//
// Jim Mahoney, Marlboro College
// April 11 2006
//
// This program is open source.
//////////////////////////////////
// Append a string to the displayed messages.
function show_message(the_string){
var message_pre = document.getElementById("message");
message_pre.innerHTML = message_pre.innerHTML + " " + the_string + "\n";
}
// Remove the displayed messages.
function clear_messages(){
var message_pre = document.getElementById("message");
message_pre.innerHTML = "";
}
// Reset everything on the page by reloading it.
// (The form data can be reset with a <input type="reset"> button,
// but that won't reset the messages or displayed results on this page,
// since they're being set by JavaScript mumbo jumbo.)
function reset_all(){
window.location.reload();
}
// Do the calculation.
function calculate(){
show_message("\n -- in function calculate() --");
// Get the form.
var calc_form = document.getElementById("calculator");
// Get the selected index from the pop-up named "operator".
var i = calc_form.operator.selectedIndex;
show_message(" i = '" + i + "'");
// Get the text (i.e. "+" or "-") from the selected option.
var op = calc_form.operator.options[i].value; // ** An "array" **
show_message(" op = '" + op + "'");
// Get the first number.
var x = parseFloat(calc_form.x.value);
show_message(" x = '" + x + "'");
if (isFinite(x)){
show_message(" and x is a number");
}
else {
show_message(" so x is *not* a number");
}
// Get the second number.
var y = parseFloat(calc_form.y.value);
show_message(" y = '" + y + "'");
if (isFinite(y)){
show_message(" and y is a number");
}
else {
show_message(" so y is *not* a number");
}
// Figure out the result.
var result;
if ( (! isFinite(x)) || (! isFinite(y)) ){
result = "<span class='warning'>OOPS - didn't find two numbers.</span>";
}
else if (op == "+"){
result = x + y;
}
else if (op == "*"){
result = x * y;
}
else if (op == "-"){
result = x - y;
}
else if (op == "/"){
result = x / y;
}
else {
result = "<span class='warning'>OOPS - unknown operator '"+op+"'.</span>";
}
// And set the html inside the tag whose id is "answer" to that result.
document.getElementById("answer").innerHTML = "<u>"+result+"</u>";
// Returning "true" from a function called by a form's "submit"
// means "submit this to the form's action URL".
// Since here we want to stay on this page, we return false instead.
return false;
}
syntax highlighted by Code2HTML, v. 0.93pm6