I am trying to learn javascript with this simple exercise and I seemed to be stumped. I need to make a simple calculation when a quantity is put in 3 separate text boxes and call my function to calculate it but no number is returned. So a quantity is put into each box, here is my attempt:
function sum2()
{
var one = document.getElementById("book_1").value;
var two = document.getElementById("book_2").value;
var three = document.getElementById("book_3").value;
if ((one == "")||(two == "")||(three == ""))
{
alert ('Error', 'values missing');
}
else
{
var sum1 = one * 19.99;
var sum2 = two * 86.00;
var sum3 = three * 55.00;
var sum = sum1 + sum2 + sum3;
document.getElementById('output').value = sum;
document.write(sum);
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Work</title>
<script type="text/javascript" src="ex4.js"></script>
</head>
<body>
<div id="container">
<h2>Order Books Online</h2>
<form action="" method="post" id=”frm”>
<fieldset>
<table border="0">
<tr>
<th>Book</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Basics of C++</td>
<td><input type="text" size="3" id="book_1" /></td>
<td>$19.99</td>
</tr>
<tr>
<td>Program Development in Perl</td>
<td><input type="text" size="3" id="book_2" /></td>
<td>$86.00</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td><input type="text" size="3" id="book_3" /></td>
<td>$55.00</td>
</tr>
</table>
<br /><br />
<input type="submit" onclick="return sum2()" value="Place Order" id="sub" />
</fieldset>
</form>
</div>
</body>
</html>
I think I have the right code but maybe just missing something. My external javascript file is called ex4.js and is in the same folder as the html file. My function is right and I believe I am calling it correctly so I have no idea where I am going wrong with this and just want the sum to be returned!!
ex.jsthen you're getting an error on your browser console telling you that the fileex4.jswasn't found. Always at least look at the browser console.sum2, but call two functions (sum()andsum2()). And when you callsum2()there are no values available for input. Use your browser's debugger, step through the code as it executes, you can see its exact behavior.