Geek Out!

live.pirillo.com

More Information

I am learning Javascript and I was building a calculator for practice.  But I cant seem to getit to work. Here is the code

<html>
<html>
<head>
<script type="text/javascript" language="javascript">
function Cac() {
var num1 = document.cac.num1.value;
var num2 = document.cac.num2.value;
var answer = document.cac.answer.value;
answer = num1*num2;
}
</script>



</head>

<body>
<form id="cac" name="cac" method="post">
  <p>What is your first number?
  <input name="num1" type="text" />
  </p>
  <p>What is your second number?
  <input name="num2" type="text" />
  </p>
  
  
   
  
  <input name="answer" type="text" readonly="true" />
  <input name="Submit" type="submit" onclick="Cac();" value="Submit" />
  
</form>

</body>
</html>

Please help

Views: 5

Reply to This

Replies to This Discussion

Please Answer.
try adding return in the onclick statement like this: onclick=" return Cac();"

I know this is not Java, but you only need ONE <html> tag at the beginning.

Two reasons:
1. Your "var answer" is not a reference to document.cac.answer.value, it's a copy of it. Simply do this instead:

function Cac() {
var num1 = document.cac.num1.value;
var num2 = document.cac.num2.value;
document.cac.answer.value = num1*num2;
}

2. Your button is a Submit button which tells the browser to post to the server, abandon the page, and load a new one using your parameters. That's not what you want at all--you simply want Javascript to execute on the current page. Simply change the type="submit" to type="button".

Here is the complete page as I think you intended it:

Mark has it. Alternatively you could return false out of your function to prevent the page from submitting I believe (I use frameworks, they handle this messy stuff, hard to remember how barebones JS does it anymore ^^).

RSS

© 2012   Created by Chris Pirillo.

Badges  |  Report an Issue  |  Terms of Service