...

View Full Version : HELP! I am a newbee. Please be gentle.



Lawds1
10-02-2008, 12:39 PM
Hi I am just starting to learn javascript but having a few problems. At the bottom is the code for a simple mathamatical programme. I can't seem to make it work. I have tried everything I can think of, but I am obviously missing something. Please help.

Here is the full code.

<html>
<head>
<title>Test2</title>

<script type="text/javascript">
var num1=parseInt(document.getElementById("n1").value);
var num2=parseInt(document.getElementById("n2").value);

function calc(){
var answer=0;

if (document.getElementById("divide").value=="divide")
answer=num1/num2;


else
answer=num1*num2;

document.getElementById("ans").value=answer;
}
</script>


</head>


<body>


<form id="form1" name="form1">

Number1:
<input type="text" Id="n1" Value="" /><br />

Number2:
<input type="text" Id="n2" Value="" /><br />


Select:
<select id="math" name="math" value="">

<option id="select" name="select" value="">------ Select Activity ------</option>
<option id="divide" name="divide" value="divide" onChange="calc();">Divide</option>
<option id="multiply" name="divide" Value="multiply">Multiply</option>
</select>


<p>Answer: <input type="text" Id="ans" name="ans" readonly="readonly" Value="" /></p>
<p><input type="reset" Id="reset" Value="Reset" /></p>

</form>

</body>

</html>

auslin
10-02-2008, 02:18 PM
Hi,

A few changes to the calc() function are needed:



function calc(){
var num1 = parseInt(document.getElementById("n1").value);
var num2 = parseInt(document.getElementById("n2").value);
var answer=0;

var sel = document.getElementById("math");
if (sel.options[sel.selectedIndex].value =="divide")
answer=num1/num2;
else answer=num1*num2;

document.getElementById("ans").value=answer;
}


Then move the function call into the <select> tag where it is actually needed:



<select id="math" name="math" value="" onchange="calc()">


Now it should work.

Lawds1
10-03-2008, 03:28 PM
Thanks for that. It really helped.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum