I'm trying to get the average of 4 grades and pass it in a text field.
It does get the average, the only part that doesn't work is the grade.value = grade;
part
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Week #10 JavaScript Assignment: Problem #1</title>
<script type = "text/javascript">
function calcgrade(one,two,three,four){
sum = parseInt(one.value) + parseInt(two.value) + parseInt(three.value) + parseInt(four.value);
grade = sum / 4;
grade.value = grade;
}
</script>
</head>
<body>
<h1>Calculate Grade</h1>
<form>
<table>
<tr>
<th>Assignment #</th>
<th>Grade</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="one" name="one"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" id="two" name="two"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text" id="three" name="three"></td>
</tr>
<tr>
<td>4</td>
<td><input type="text" id="four" name="four"></td>
</tr>
<tr><td colspan="2"><input type="button" onclick="calcgrade(one, two, three, four)" value="Calculate Grade"></td></tr>
<tr>
<td>Grade:</td>
<td><input type="text" id="grade" name="grade"></td>
</tr>
</td>
</form>
</body>
</html>
you need to get the element in javascript
gradeEle = document.getElementById("grade");
gradeEle.value = grade;
采用
document.getElementById('grade').value=grade;
它应该是:
document.getElementById('grade').value = grade;
You're trying to reuse grade
for 2 different values, but it can only keep one of them.
grade.value = grade;
// ^ element
// ^ division result
You'll either want to use a different variable:
var result = sum / 4;
grade.value = result;
Or, you can skip it entirely:
grade.value = sum / 4;
Though, do note that automatic globals for id
s aren't always guaranteed and it's not usually recommended to depend on them.
You can instead access any name
d form items from the <form>
and vice versa.
<input type="button" onclick="calcgrade(this.form)" ...>
function calcgrade(form){
var sum = parseInt(form.one.value) + parseInt(form.two.value) + parseInt(form.three.value) + parseInt(form.four.value);
form.grade.value = sum / 4;
}
Or, use getElementById()
to find each specifically:
function calcgrade() {
var grade = document.getElementById('grade');
var one = document.getElementById('one');
// etc.
}
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.