开发者

Need help on simple calculator

<html>
<head>
<script language="javascript">
function fadd()
{
var first,sec,res;
first=parsefloat(document.forms[0].txt1st.value);
sec=parsefloat(document.forms[0].txt2nd.value);
res=first+sec;
document.forms[0].txtres.value=res;
}
</script>
</head>


<body>
<form>
Enter 1st number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="txt1st" id="txt1st" type="text">
</br>
Enter 2nd number &nbsp;&nbsp;&nbsp;&am开发者_JAVA百科p;nbsp;&nbsp;<input name="txt2nd" id="txt2nd" type="text">
</br>
Result &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;
<input name="txtres" id="txtres" type="text">
</br>
<input name="btnadd" id="btnadd" type="button" value="+" onclick="fadd()">
<input name="btnsub" id="btnsub" type="button" value="-" onclick="fminus()">
<input name="btndiv" id="btndiv" type="button" value="%" onclick="fdiv()">
<input name="btnmul" id="btnmul" type="button" value="*" onclick="fmult()">
</form> 
</body>
</html>


Two things:

parsefloat should be parseFloat. Function names are case-sensitive.

1st is not a legal ID (and I don't think it's a legal name, either). Also, you cannot refer to a non-identifier (1st is not an identifier because it begins with a digit) in dot notation (x.y.z). You could try document.forms[0]['1st'].value, or you could try renaming 1st to first (and 2nd to second).


EDIT: This answer was posted before the question was updated.

You cannot use the dot notation for property names that start with a number.

Don't use document.forms[0].1st. Use document.getElementById('1st'). The same applies for 2nd.

var x = {};

x['1st'] = 10;

console.log(x['1st']); // This works
console.log(x.1st);    // This doesn't - Syntax error


Also, you should change this line:

document.forms[0].textres.value=res;

To this:

document.forms[0].txtres.value=res;

After listening to the advice of the other posts here AND doing this, your code should work fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜