简体   繁体   中英

input.value=<variable> returning static value [Javascript]

I'm very new to this, and have recently made a very primitive program that will calculate x^y for integer values of x and y. The script

var total = 1;
var power = 0;
var x = 4;
var y = 2;
while(power<=(y-1))
{power+=1;
 total*=(x);}
print(total);

works in a javascript console, but when I try to make a simple HTML file

<html>
<title>Score Verifier</title>
<head>
<script language="javascript">
function calculate()
{
var x=document.getElementById('x');
var y=document.getElementById('y');
var result=document.getElementById('result');
var total = 1;
var power = 0;
while(power<=(y-1))
{
power+=1;
 total*=(x+(power-power));}
result.value=total
}
</script>
</head>
<body>
Calculate x^y<br />
Enter x: <input id="x" type="text" /><br />
Enter y: <input id="y" type="text" /><br />
<input id="calc" type="button" value="Calculate" onclick="calculate()" /><br />
Result: <input id="result" type="text" />
</body>
</html>

I always get a "1" in the result input. How do I make it give the total from the while loop?

You always get 1 (the initial value), because your code never enters into while loop. Your x and y are of type object , thats why y - 1 will return NaN (not-a-number) and thats why power<=(y-1) will always be false .

You should get the value of input element (which will be string ) and then convert it to integer:

var x=parseInt(document.getElementById('x').value);
var y=parseInt(document.getElementById('y').value);

Demo: http://jsfiddle.net/73xnS/

You are getting the value by document.getElementById('x'); which is wrong but should be something like

var x=parseInt(document.getElementById('x').value, 10);
//-------------------------------------Use----^

OR

var x = +document.getElementById('x').value;
//------^---this operator converts string to number

Instead of

var x=document.getElementById('x');

You can use the parseInt() function to convert the string to number.

DEMO

This always returns that DOM object

var x=document.getElementById('x');
var y=document.getElementById('y');
var result=document.getElementById('result');

You can use

document.getElementById('elementid').value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM