I want to average numbers froms four(4) input fields(with Min. value of 0 and Max. value of 100) and show the result dynamically (i.e. without reloading the page) immdiately any of the fields is filled. Then in the last column, is for the grade which is also dynamic. Should show A for value between 80 and 100 with a blue coloured cell, B for value between 60 and 80 with a green coloured cell and so on. But the grade is not working. I also want to input the data into a database dynamically using ajax but I don't know how to go about it. Below is what I have come up with. Thanks in advance. Below is the code
$('#input1').keyup(function() {
evaluate();
});
$('#input2').keyup(function() {
evaluate();
});
$('#input3').keyup(function() {
evaluate();
});
$('#input4').keyup(function() {
evaluate();
});
var evaluate = function() {
var input1 = parseInt($('#input1').val());
var input2 = parseInt($('#input2').val());
var input3 = parseInt($('#input3').val());
var input4 = parseInt($('#input4').val());
if (isNaN(input1) || isNaN(input2) || isNaN(input3) || isNaN(input4)) {
$('#error').text('Inputs must be numbers');
} else {
var ave = (input1 + input2 + input3 + input4) / 4;
$('#total').text(input1 + input2 + input3 + input4);
$('#ave').text(ave);
switch (ave) {
case 100 <= ave >= 80:
$('#grade').text('<div bgcolor="blue">A</div>');
break;
case 80 < ave >= 60:
$('#grade').text('<div bgcolor="green">B</div>');
break;
case 60 < ave >= 40:
$('#grade').text('<div bgcolor="yellow">C</div>');
break;
case 40 < ave >= 20:
$('#grade').text('<div bgcolor="red">D</div>');
break;
case 20 < ave >= 0:
$('#grade').text('<div bgcolor="green">E</div>');
break;
default:
$('#grade').text('<div>--</div>');
}
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<th>Input 1</th>
<th>Input 2</th>
<th>Input 3</th>
<th>Input 4</th>
<th>Total</th>
<th>Average</th>
<th>Grade</th>
</tr>
<tr>
<td>
<input id="input1" name="input1" size="1px" />
</td>
<td>
<input id="input2" name="input2" size="1px" />
</td>
<td>
<input id="input3" name="input3" size="1px" />
</td>
<td>
<input id="input4" name="input4" size="1px" />
</td>
<td id="total"></td>
<td id="ave"></td>
<td id="grade"></td>
</tr>
</table>
<div id="error"></div>