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 <input name="txt1st" id="txt1st" type="text">
</br>
Enter 2nd number &am开发者_JAVA百科p;nbsp; <input name="txt2nd" id="txt2nd" type="text">
</br>
Result
<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.
精彩评论