我正在开发一个程序来输入学生的标记并对其进行添加操作。我的代码是:
<html>
<head>
<script type="text/javascript">
function fstudent()
{
var m1 =eval(document.getElementById("txtmarks1")).value;
var m2 =eval(document.getElementById("txtmarks2")).value;
var m3 =eval(document.getElementById("txtmarks3")).value;
var total =m1+m2+m3;
alert("total marks is"+total);
}
</script>
</head>
<body>
<form name="STUDENT">
<table>
<tr>
<td>Enter StudentNo:</td>
<td><input type="number" id="numSno"></td>
</tr>
<tr>
<td>Enter StudentName:</td>
<td><input type="text" id="txtSname"></td>
</tr>
<tr>
<td>Enter Marks1:</td>
<td><input type="text" id="txtmarks1"></td>
</tr>
<tr>
<td>Enter Marks2:</td>
<td><input type="text" id="txtmarks2"></td>
</tr>
<tr>
<td>Enter Marks3:</td>
<td><input type="text" id="txtmarks3"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Calculate Total Marks" onclick="fstudent()"></td>
</tr>
</table>
</form>
</body>
</html>
当我对它执行加法运算时,它返回一个字符串值,但是当我对它执行乘法运算时,它返回一个整数值。我尝试使用parseInt
方法将string
转换为int
,但它也仅提供字符串值。
答案 0 :(得分:0)
如果只能输入整数:
var m1 = parseInt(document.getElementById("txtmarks1").value, 10);
如果允许浮动:
var m1 = parseFloat(document.getElementById("txtmarks1").value);
答案 1 :(得分:0)
<html>
<head>
<script type="text/javascript">
function fstudent() {
var m1 = document.getElementById("txtmarks1").value;
var m2 = document.getElementById("txtmarks2").value;
var m3 = document.getElementById("txtmarks3").value;
var total = parseInt(m1) + parseInt(m2) + parseInt(m3);
alert("total marks is" + total);
}
</script>
</head>
<body>
<form name="STUDENT">
<table>
<tr>
<td>
Enter StudentNo:
</td>
<td>
<input type="number" id="numSno">
</td>
</tr>
<tr>
<td>
Enter StudentName:
</td>
<td>
<input type="text" id="txtSname">
</td>
</tr>
<tr>
<td>
Enter Marks1:
</td>
<td>
<input type="text" id="txtmarks1">
</td>
</tr>
<tr>
<td>
Enter Marks2:
</td>
<td>
<input type="text" id="txtmarks2">
</td>
</tr>
<tr>
<td>
Enter Marks3:
</td>
<td>
<input type="text" id="txtmarks3">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="Calculate Total Marks" onclick="fstudent()">
</td>
</tr>
</table>
</form>
</body>
</html>