View Full Version : Easy Javascript help required for a newbie..

Feb 28th, 2007, 07:02 PM
I've just started learniing javascript and I need help with this little uni project.

The brief:
Design an online n! calculator for the following problem:

Create a Web page which contains a form with a text input field and a button.

Text input field: input a number n between 0 and 20;
Output: when the Calculate button is clicked, use onclick to call a function to display the value of y, if n>20, display the message: “Please input a number between 0 to 20!”

heres what I got:

<title> Web Programming</title>
<script type="text/javascript" language="javascript">
function calculator(n){
var n= document.nform.number.value);
var y="1";
if(n=="0") {
window.alert("0 = 1");
else if (n>"0" && n<="20") {
for(i="1";i<=n; i++)

window.alert(“Please input a number between 0 to 20!”);
<body bgcolor="silver">
<p>Please enter a number between 0 and 20!</p>
<form name="nform">
<input type="text" size=30 name="number"><br><br>
<input type="button" name="button1" value="calcuate" onclick="calculator(document.nform.number.value);">

Wont work: Any help?:confused:

Feb 28th, 2007, 07:45 PM
I see at least one syntax error off the top of the bat.

var n= document.nform.number.value);

Turn on error checking in your browser to display error messages (IE) or check the Javascript Console (FF).

And please use the [ code] code here [ /code] (no spaces) BB code tags to format your code nicely. The little # sign in the editor is a short cut.

Feb 28th, 2007, 07:53 PM
is there a reason all your numbers are encased in quotes?

i dont think it makes a difference but it looks weird.

like var y = 1 is fine otherwise its a string

Mar 1st, 2007, 12:45 AM
Actually Rappa's point is right on target...
All of your "numbers" are actually strings (even the value from the input box!)
Aside from the errant parenthesis, you'll need to use numbers to do math. Get rid of the quotes around all of your hard-coded numbers and convert the input's value to a number as well....

function calculator(n)
// Initialize variables...
// The next line is not needed, but then again, it wasn't necessary in the original either...
if (!arguments[0]) var n= document.nform.number.value;
var y=1;
n=parseInt(n); // This will convert "n" to an integer

// Do the Math
window.alert("0 = 1");
} else if (n>"0" && n<="20") {
for(i=1;i<=n; i++)
} else {
window.alert(“Please input a number between 0 to 20!”);