Have created a basic form, three drop down lists and a button. im tryn to multiply the three values in the down lists. i have to pass the data up to the function. i have ran the code just keep getting 0 as the result?? I don't think I'm passing the data from from up to the function correctly?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
function multiply(number1, number2, number3)
{
var firstnum=0;
var secondnum=0;
var thirdnum=0;
var answer;
firstnum=parseInt(number1);
secondnum=parseInt(number2);
thirdnum==parseInt(number3);
answer=(firstnum*secondnum*thirdnum);
alert(answer)
}
</script>
<form name="Example1">
Number 1:
<select id="num1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br/>
Number 2:
<select id="num2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br/>
Number 2:
<select id="num3">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br/>
<input type=button value="muliply" onclick="multiply(num1.value, num2.value, num3.value)" />
</form>
</body>
</html>
-
Please try to check the syntax is proper always...@Francis GallDinesh Kanivu– Dinesh Kanivu2013年10月03日 11:38:57 +00:00Commented Oct 3, 2013 at 11:38
2 Answers 2
Your problem is:
thirdnum==parseInt(number3); is a comparison, not an assignment, so thirdnum will always be 0.
Since you are multiplying by thirdnum, and anything ×ばつ 0 is 0, you will always get 0 as the output.
Change == to =.
This would have been picked up if you had QAed your code with JS Hint.
Your bad practises which you should fix are:
num1.valueassumes global JS variables will be created for every element with an id. Don't assume that, usedocument.getElementByIdparseInt(number1)doesn't have a radix. Always specify the number system you are using (normally base 10) so it isn't inferred from the data for unexpected results:parseInt(number1, 10);<form name="Example1">, the name attribute on forms is a legacy from before theidattribute had come around properly. Useidto identify elements for client side code.onclickattributes do a poor job of separating concerns. UseaddEventListener(or a library such as YUI or jQuery if you need to support old versions of IE).