Grading system in Javascript - javascript

Can anyone please help me in this problem.
Write a program that takes input from user to read roll no and marks of 5 subjects and calculate the total and Average of the marks. Making sure that each subject marks are not greater than 100. Then making grading system. You have to calculate grade on the basis of average.
You have to print the grade according to the following criteria:
If average is greater than 80 and less than 100, Grade is A
If average is greater than 75 and less than 80, Grade is B
HERE IS MY CODE: How can I include conditions in this code.
function grading() {
var val1 = parseInt(document.getElementById("num1").value);
var val2 = parseInt(document.getElementById("num2").value);
var val3 = parseInt(document.getElementById("num3").value);
var val4 = parseInt(document.getElementById("num4").value);
var final = val1 + val2 + val3 + val4;
document.getElementById("result").innerHTML = +final + " / 400 ";
}
function average() {
var val1 = parseInt(document.getElementById("num1").value);
var val2 = parseInt(document.getElementById("num2").value);
var val3 = parseInt(document.getElementById("num3").value);
var val4 = parseInt(document.getElementById("num4").value);
var final1 = val1 + val2 + val3 + val4;
var total = final1 / 4;
document.getElementById("avrg").innerHTML = +total;
}
HTML Code :
<body>
<label>English</label>
<input type="text" id="num1"><br>
<label>English</label>
<input type="text" id="num2"><br>
<label>English</label>
<input type="text" id="num3"><br>
<label>English</label>
<input type="text" id="num4"><br>
<button onClick="grading()">Total</button>
<p id="result"></p><br>
<button onClick="average()">Average</button><br>
<p id="avrg"></p>
<button onClick="system()">Grade</button><br>
<p id="grad"></p>
</body>

You have to create the function to show the final grade. Declare the variable total so that you can check that inside the function to show the expected grade.
Condition for the range 80 to 100 - Grade A
if(total >= 80 && total <= 100)
Condition for the range 75 to 79 - Grade B
else if(total >= 75 && total < 80)
Please Note: I have change the function name from system to gradeFinal which is more meaningful. I will also suggest you to use textContent instead of innerHTML which is more faster and predictable.
You can try the following way:
function grading(){
var val1 = parseInt(document.getElementById("num1").value);
var val2 = parseInt(document.getElementById("num2").value);
var val3 = parseInt(document.getElementById("num3").value);
var val4 = parseInt(document.getElementById("num4").value);
var final = val1 + val2 + val3 + val4;
document.getElementById("result").textContent = +final + " / 400 ";
}
var total;
function average(){
var val1 = parseInt(document.getElementById("num1").value);
var val2 = parseInt(document.getElementById("num2").value);
var val3 = parseInt(document.getElementById("num3").value);
var val4 = parseInt(document.getElementById("num4").value);
var final1 = val1 + val2 + val3 + val4;
total = final1 / 4;
document.getElementById("avrg").textContent = +total;
}
function gradeFinal(){
if(total >= 80 && total <= 100)
document.getElementById("grad").textContent = 'A';
else if(total >= 75 && total < 80)
document.getElementById("grad").textContent = 'B'
}
document.querySelectorAll('input[type=text]').forEach(function(input){
input.addEventListener('input',limitRange);
});
function limitRange() {
if (this.value < 0) this.value = 0;
if (this.value > 100) this.value = 100;
}
<label>English</label>
<input type="text" id="num1"><br>
<label>English</label>
<input type="text" id="num2"><br>
<label>English</label>
<input type="text" id="num3"><br>
<label>English</label>
<input type="text" id="num4"><br>
<button onClick="grading()">Total</button>
<p id="result"></p><br>
<button onClick="average()">Average</button><br>
<p id="avrg"></p>
<button onClick="gradeFinal()">Grade</button><br>
<p id="grad"></p>

Related

return to zero after reach max value and add the remaining value javascript

sorry i am newbie here
i need some help,
this case like notice a time.
when real time passes input value, then span with id alertLabel will change.
the problem is, if input value plus with input with id Duration will exceed real minutes or hours.
this is my code example.
javascript.js
var alertLabel = document.getElementById("alertLabel");
var less = document.getElementById("lessThan").value.replace(":", "");
var late = document.getElementById("timeIn").value.replace(":", "");
var duration = parseInt(document.getElementById("Duration").value);
var outs = document.getElementById("timesOut").value.replace(":", "");
var lessInt = parseInt(less);
var lateInt = parseInt(late);
var outsInt = parseInt(outs);
var durationOut = outsInt + duration; // this will be exceed
var durationIn = lateInt + duration; // this will be exceed
function getAlert() {
let times = new Date();
let sh = times.getHours() + "";
let sm = times.getMinutes() + "";
let ss = times.getSeconds() + "";
let shLong = sh.length == 1 ? "0" + sh : sh;
let smLong = sm.length == 1 ? "0" + sm : sm;
let ssLong = ss.length == 1 ? "0" + ss : ss;
let shSm = shLong + smLong;
document.getElementById("clock").innerHTML = shLong + ":" + smLong + ":" + ssLong;
if (shSm >= outsInt && shSm < durationOut) {
alertLabel.innerHTML = "OUT!!";
} else if (shSm >= lessInt && shSm < lateInt) {
alertLabel.innerHTML = "hurry up, don't be late!!";
} else if (shSm >= lateInt && shSm < durationIn) {
alertLabel.innerHTML = "LATE!!";
} else {
if (shLong >= 21 || shLong <= 4) {
alertLabel.innerHTML = "good dream tonight !!";
} else if (shLong >= 5 && shLong <= 11) {
alertLabel.innerHTML = "spirit Morning !!";
} else if (shLong >= 12 && shLong <= 17) {
alertLabel.innerHTML = "happy Noon !!";
} else if (shLong >= 18 && shLong <= 20) {
alertLabel.innerHTML = "nice evening !!";
}
}
}
<!doctype html>
<html>
<head>
<title></title>
</head>
<body onload="getAlert();setInterval('getAlert()',1000)">
<span id="clock"></span>
<span id="alertLabel"></span>
<div></div>
<input class="" type="text" id="lessThan" value="13:45" name="lessThan"> <!-- when time to in is near -->
<input class="" type="text" id="timeIn" value="13:48" name="timeIn"> <!-- time in and get alert Late -->
<input type="text" id="timesOut" value="13:55" name="timesOut"> <!-- value time to out and get alert Out -->
<input type="text" name="Duration" id="Duration" value="5"> <!-- duration alert for id timeIn and timesOut if more than 100 is the problem, this input as minute -->
</body>
</html>
this is my last try, example in input id timeIn
var a = document.getElementById("timeIn").value.split(":");
for (var i = 0; i < duration; i++){
var b = parseInt(a[0]); // this for hours
var c = parseInt(a[1]); // this for minutes
var x = c + i;
if (x >= 60){
var n = b + 1;
x = x-60;
}
console.log(x);
}
in my last try, in log var x return to zero just once
and the question is, if input value with id duration more than 100, how looping, if each var x reach value (60) his return to zero and var c plus 1 each var x reach 60.
maybe anyone have an easier one to solve this case.
sorry if the explanation is unclear.

Is there a way to split inserted value for example 1234567890 to 12345 and 67890?

Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);

Javascript total return NaN for 4 digits num

Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}

Adding two form variables with calculating and comparing

I have items "item1 costs $1" and "item2 costs $2"
I made a simple form to calculate the total price of both BUT if the customer will purchase more than 50 items (total items = item1 + item2) I will give him a 50% discount which means the final price will be divided by 2 BUT only if we the total is more than "50".
What I am getting that the price is getting divided by 2 even if the total is only = 10 !!
Here's the jsfiddle:
http://jsfiddle.net/2yTLp/225/
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
var total = x.value + y.value;
if( total >= 50 ){
d.innerHTML = ((x.value * 1.00) + (y.value * 2.00)) / 2;
}
else{
d.innerHTML = (x.value * 1.00) + (y.value * 2.00);
}
}
x.onblur = calculate;
calculate();
#d{
text-indent:20px;
}
<h3>Calculate</h3>
item1 <input id="x" data-in="" type="number" /><br>
<br>
item2 <input id="y" data-in="" type="number" /><br>
<br>
Please Pay and amount of <span id="d"></span>
it's very easy but can't figure it out.
Regards,
You are concatenating strings instead of sum numbers. Please, convert the values to numbers and it works perfectly. See the line commented:
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
//here you need to convert values to numbers
var total = Number(x.value) + Number(y.value);
if( total >= 50 ){
d.innerHTML = ((x.value * 1.00) + (y.value * 2.00)) / 2;
}
else{
d.innerHTML = (x.value * 1.00) + (y.value * 2.00);
}
}
x.onblur = calculate;
calculate();
#d{
text-indent:20px;
}
<h3>Calculate</h3>
item1 <input id="x" data-in="" type="number" /><br>
<br>
item2 <input id="y" data-in="" type="number" /><br>
<br>
Please Pay and amount of <span id="d"></span>
The explanation is if you concatenate this:
var one = "10";
var two = "15";
var result = one + two ; // result string "1015"
But if you change to numbers the sum is perfect
var one = "10";
var two = "15";
var result = Number(one) + Number(two) ; // result int 25
It is very straight and simple
Your code is correct except one thing, you didn't use parseInt,
currently you are concatenating the values instead of adding,
so just replace this code
var total = x.value + y.value;
with this one
var total = parseInt(x.value) + parseInt(y.value);
That's it :)

Calculating a student grade in JavaScript

I've got an HTMl form to input student names and grades in which should use JavaScript to calculate a grade that is then printed on the screen. My HTMl works fine if I comment the meat of my JavaScript out, but not if I don't. The error is somewhere in the code that I commented out, but I just can't find it (or them).
The HTML form will submit, alert the user, and show my message correctly as long as it is fed a concrete grade and score instead of trying to fetch it through getGrade() and getScore(). This is why I know the bug is in the JavaScript.
I've run the page in the JavaScript console to look for bugs, but there are no red flag errors.
This is my first HTML/JavaScript program, and I not very good at it. Anyway, it's a day late and in less than two hours, it will be two days late, so if anyone could help, I'd appreciate it hugely. Here's the code, sorry if it's too much:
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
/*
var s1 = new Student(fname, lname);
for (var i = 0; i < classworkArray.length; i++)
s1.addGradedActivity(classworkArray[i]);
for (var i = 0; i < homeworkArray.length; i++)
s1.addGradedHomework(homeworkArray[i]);
s1.setMidterm(valMidterm, lMidterm);
s1.setFinal(valFinal, lFinal);
var grade = s1.getGrade();
var score = s1.getScore();
*/
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
alert(document.getElementById("FirstName").value);
return false;
}
/*
function Coursework(){
var sum = 0;
var num = 0;
this.addScore = function(score){
if (score < 0) {score = 0;}
if (score > 100) {score = 100;}
sum += score;
num++;
}
this.getAverage = function(){
return (sum/num);
}
}
function Exam(){
var score = 0;
var grade = "";
this.Exam = function(Score, Grade)
{
if (Score < 0) {Score = 0;}
if (Score > 100) {Score = 100;}
score = Score;
if (Grade != "A" && Grade != "B" && Grade !="C"
&& Grade !="D" && Grade != "F")
{
console.log("You have submitted a bad grade for an Exam, value of:G.");
Grade = "F";
}
grade = Grade;
}
this.getScore = function(){
return score;
}
this.getGrade = function(){
return grade;
}
}
function Student(){
var firstName;
var lastName;
var midterm;
var finalExam;
var homework = new Coursework();
var inclass = new Coursework();
this.Student = function(first, last){
firstName = first;
lastName = last;
}
this.setMidterm = function(score, grade){
midterm = new Exam(score, grade);
}
this.setFinal = function(score, grade){
finalExam = new Exam(score, grade);
}
this.addGradedHomework = function(score){
homework.addScore(score);
}
this.addGradedActivity = function(score){
inclass.addScore(score);
}
this.getFinalGrade = function(totalScore)
{
var grade = totalGrade(totalScore);
var grade2 = "F";
var midGrade = this.convertGrade(midterm.getGrade());
var finGrade = this.convertGrade(finalExam.getGrade());
if (midGrade < finGrade)
{
grade2 = midterm.getGrade();
}
else
{
grade2 = finalExam.getGrade();
}
if (convertGrade(grade) > convertGrade(grade2))
return(grade);
else
return(grade2);
}
this.totalGrade = function(totalScore)
{
var totalGrade = "F";
if (totalScore >= 90)
totalGrade = "A";
else if (totalScore >= 80)
totalGrade = "B";
else if (totalScore >= 70)
totalGrade = "C";
else if (totalScore >= 60)
totalGrade = "D";
else
totalGrade = "F";
return (totalGrade);
}
this.convertGrade = function(letter)
{
var num = 0;
if (letter === "A")
num = 4;
else if (letter === "B")
num = 3;
else if (letter === "C")
num = 2;
else if (letter === "D")
num = 1;
else
num = 0;
return(num);
}
this.getScore = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
return totalScore;
}
this.getGrade = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
var grade = getFinalGrade(totalScore);
return grade;
}
}
*/
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1" onsubmit="return calculateGrade()" style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="submit" value="Submit">
</form>
<p id="p1" style="display:none">Final course grade for <span id="fname">Joe</span> <span id="lname">Peterson</span> is: <span id="span1">X</span> (<span id="span2">yy</span>%)</p>
</body>
</html>

Categories

Resources