Problem
I have a table with 2 rows and 3 columns, the third column is where results are displayed.
My goal is to make the code to display 25% in the first row if (the difference between x and y is greater than 3 but less than 11).
And display 25% in the second row if (w + z > 3) is true and display 20% if (w + y = 3) is true.
How do I solve this issue?
Attempt
<!DOCTYPE html>
<html>
</head>
<BODY>
<script>
document.addEventListener("change", function() {
var x = document.getElementById("hp").value,
y = document.getElementById("ap").value,
w = document.getElementById("hc").value,
z = document.getElementById("ac").value,
text;
if (x - y > 3 && y - x < 11) {
text = "<span class='green'>25%</span>";
} else if (y - x > 3 && x - y < 11) {
text = "<span class='green'>25%</span>";
} else {
text = "<span class='red'>10%</span>";
}
document.getElementById("pr").innerHTML = text;
if (w + z > 3) {
text = "<span class='green'>25%</span>";
} else if (w + z = 3) {
text = "<span class='green'>20%</span>";
} else {
text = "<span class='red'>10%</span>";
}
document.getElementById("cr").innerHTML = text;
})
</script>
<style>
.green {
color: green;
}
.red {
color: red;
}
.yellow {
color: yellow
</style>
<TABLE align="center" BORDER="1" WIDTH="" CELLPADDING="4" CELLSPACING="3">
<TR>
<TD id="">
<p>HOMEPOSITION:</p>
<input type="number" id="hp">
</TD>
<TD id="">
<p>AWAYPOSITION:</p>
<input type="number" id="ap">
</TD>
<TD id="pr"></TD>
</TR>
<TR>
<TD id="">
<p>HOMECAST:</p>
<input type="number" id="hc">
</TD>
<TD type="number" id="">
<p>AWAYCAST:</p>
<input type="number" id="ac">
</TD>
<TD id="cr"></TD>
</TR>
</TABLE>
</html>
It seems to be a problem with an operator (= vs ==):
Code
<!DOCTYPE html>
<html>
<head>
<style>
.green {
color: green;
}
.red {
color: red;
}
.yellow {
color: yellow
</style>
</head>
<BODY>
<TABLE align="center" BORDER="1" WIDTH="" CELLPADDING="4" CELLSPACING="3">
<TR>
<TD id="">
<p>HOMEPOSITION:</p>
<input type="number" id="hp">
</TD>
<TD id="">
<p>AWAYPOSITION:</p>
<input type="number" id="ap">
</TD>
<TD id="pr"></TD>
</TR>
<TR>
<TD id="">
<p>HOMECAST:</p>
<input type="number" id="hc">
</TD>
<TD type="number" id="">
<p>AWAYCAST:</p>
<input type="number" id="ac">
</TD>
<TD id="cr"></TD>
</TR>
</TABLE>
<script>
document.addEventListener("change", function() {
var x = document.getElementById("hp").value,
y = document.getElementById("ap").value,
w = document.getElementById("hc").value,
z = document.getElementById("ac").value,
text;
if (x - y > 3 && y - x < 11) {
text = "<span class='green'>25%</span>";
} else if (y - x > 3 && x - y < 11) {
text = "<span class='green'>25%</span>";
} else {
text = "<span class='red'>10%</span>";
}
document.getElementById("pr").innerHTML = text;
if (w + z > 3) {
text = "<span class='green'>25%</span>";
} else if (w + z == 3) {
text = "<span class='green'>20%</span>";
} else {
text = "<span class='red'>10%</span>";
}
document.getElementById("cr").innerHTML = text;
})
</script>
</BODY>
</html>
Related
I have 20 unique random numbers and check between 6 unique numbers.
the first check works, but after refreshing the 6 unique numbers, of the numbers return undefined.
I've given the full code so people can tinker with it.
no need for CSS, that is just to identify different numbers.
sorry for the long codes, it's just how i keep my code tidy.
var num = [];
var com = [];
var s = 0;
var j = 0;
function twenty() {
for (i = 0; i < 20; i++) {
com[i] = Math.floor(Math.random() * 49) + 1;
var x = com.length;
x = x - 1;
for (y = 0; y < x; y++) {
var t1 = com[y];
var t2 = com[i]
while (t1 == t2) {
com[x] = Math.floor(Math.random() * 49) + 1;
t1 = com[x];
}
}
}
for (i = 0; i < 5; i++) {
for (t = 0; t < 4; t++) {
document.getElementsByClassName(t)[i].innerHTML = com[s];
s++;
}
}
}
function calc() {
num = [];
var out = "";
var z = document.getElementById('max').value;
for (i = 0; i < z; i++) {
num[i] = Math.floor(Math.random() * 49) + 1;
var x = num.length;
x = x - 1;
for (y = 0; y < x; y++) {
var t1 = num[y];
var t2 = num[i]
while (t1 == t2) {
num[x] = Math.floor(Math.random() * 49) + 1;
t1 = num[x];
}
}
out += num[i] + ", ";
}
document.getElementById('num').innerHTML = out;
}
function check() {
s = 0;
if (j == 0) {
for (i = 0; i < 5; i++) {
for (t = 0; t < 4; t++) {
var set = 0;
var test1 = document.getElementsByClassName(t)[i].innerHTML;
var y = num.length;
for (x = 0; x < y; x++) {
var comp = num[x];
if (test1 == comp) {
set = 1;
}
if (set == 1) {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='yes' >";
} else if (test1 == undefined) {
document.getElementsByClassName(t)[i].innerHTML = "undefined";
} else {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='no' >";
}
}
s++;
}
}
j = 1;
} else {
for (i = 0; i < 5; i++) {
for (t = 0; t < 4; t++) {
var set = 0;
var test1 = document.getElementById(s).value;
var y = num.length;
for (x = 0; x < y; x++) {
var comp = num[x];
if (test1 == comp) {
set = 1;
}
if (set == 1) {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='yes' >";
} else if (test1 == undefined) {
document.getElementsByClassName(t)[i].innerHTML = "undefined";
} else {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='no' >";
}
}
s++;
}
}
}
}
html{
}
input[type=button].yes{
background: green;
border: none;
}
input[type=button].no{
background: red;
border: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src='code.js'></script>
</head>
<body onload='twenty()'>
<h1>lottery randomizer</h1>
<table border='1'>
<tr>
<td>randomize numbers
</td>
<td>choose number of random numbers
</td>
</tr>
<tr>
<td>
<input type='button' onclick='calc()' value='randomize'>
</td>
<td>
<input type='number' value='6' id='max'>
</td>
</tr>
</table>
<table>
<tr>
<td>
your numbers are:
<div id='num'>
</div>
</td>
</tr>
</table>
<table border='1' class='table'>
<tr>
<td>
<div class='0' id='1'>
</div>
</td>
<td>
<div class='0' id='2'>
</div>
</td>
<td>
<div class='0' id='3'>
</div>
</td>
<td>
<div class='0' id='4'>
</div>
</td>
<td>
<div class='0' id='5'>
</div>
</td>
</tr>
<tr>
<td>
<div class='1' id='1'>
</div>
</td>
<td>
<div class='1' id='2'>
</div>
</td>
<td>
<div class='1' id='3'>
</div>
</td>
<td>
<div class='1' id='4'>
</div>
</td>
<td>
<div class='1' id='5'>
</div>
</td>
</tr>
<tr>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
</tr>
<tr>
<td>
<div class='3' id='1'>
</div>
</td>
<td>
<div class='3' id='2'>
</div>
</td>
<td>
<div class='3' id='3'>
</div>
</td>
<td>
<div class='3' id='4'>
</div>
</td>
<td>
<div class='3' id='5'>
</div>
</td>
</tr>
</table>
<input type='button' onclick='check()' value='check numbers'>
</body>
</html>
When I'm calculating my age, the code below showing "xxx days left for your next birthday". But I want to know, how many days left for my certain birthday. (i.e: I want to know how many days left for my 30th birthday. The result should be like this "xxx days left for your 30th birthday" instead of next birthday.)
What change I need to do?
function wr_document() {
var w = new Date();
var s_d = w.getDate();
var s_m = w.getMonth() + 1;
var s_y = w.getFullYear();
document.cir.len11.value = s_d;
document.cir.len12.value = s_m;
document.cir.len13.value = s_y;
}
function isNum(arg) {
var args = arg;
if (args == "" || args == null || args.length == 0) {
return false;
}
args = args.toString();
for (var i = 0; i < args.length; i++) {
if ((args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") && args.substring(i, i + 1) != ".") {
return false;
}
}
return true;
}
function checkday(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 31) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
function checkmon(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 12) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
function checkyear(aa) {
var val = aa.value;
var valc = val.substring(0, (val.length - 1));
if (val.length > 0 && val.length < 7) {
if (!isNum(val) || val == 0) {
aa.value = valc;
} else if (val < 1 || val > 275759) {
aa.value = "";
}
} else if (val.length > 4) {
aa.value = valc;
}
}
function checkleapyear(datea) {
if (datea.getYear() % 4 == 0) {
if (datea.getYear() % 10 != 0) {
return true;
} else {
if (datea.getYear() % 400 == 0)
return true;
else
return false;
}
}
return false;
}
function DaysInMonth(Y, M) {
with(new Date(Y, M, 1, 12)) {
setDate(0);
return getDate();
}
}
function datediff(date1, date2) {
var y1 = date1.getFullYear(),
m1 = date1.getMonth(),
d1 = date1.getDate(),
y2 = date2.getFullYear(),
m2 = date2.getMonth(),
d2 = date2.getDate();
if (d1 < d2) {
m1--;
d1 += DaysInMonth(y2, m2);
}
if (m1 < m2) {
y1--;
m1 += 12;
}
return [y1 - y2, m1 - m2, d1 - d2];
}
function calage() {
var curday = document.cir.len11.value;
var curmon = document.cir.len12.value;
var curyear = document.cir.len13.value;
var calday = document.cir.len21.value;
var calmon = document.cir.len22.value;
var calyear = document.cir.len23.value;
if (curday == "" || curmon == "" || curyear == "" || calday == "" || calmon == "" || calyear == "") {
alert("Please fill all the values and click 'Go'");
} else if (curday == calday && curmon == calmon && curyear == calyear) {
alert("Today your birthday & Your age is 0 years old")
} else {
var curd = new Date(curyear, curmon - 1, curday);
var cald = new Date(calyear, calmon - 1, calday);
var diff = Date.UTC(curyear, curmon, curday, 0, 0, 0) -
Date.UTC(calyear, calmon, calday, 0, 0, 0);
var dife = datediff(curd, cald);
document.cir.val.value = dife[0] + " years, " + dife[1] + " months, and " + dife[2] + " days";
var secleft = diff / 1000 / 60;
document.cir.val3.value = secleft + " minutes since your birth";
var hrsleft = secleft / 60;
document.cir.val2.value = hrsleft + " hours since your birth";
var daysleft = hrsleft / 24;
document.cir.val1.value = daysleft + " days since your birth";
//alert(""+parseInt(calyear)+"--"+dife[0]+"--"+1);
var as = parseInt(calyear) + dife[0] + 1;
var diff = Date.UTC(as, calmon, calday, 0, 0, 0) -
Date.UTC(curyear, curmon, curday, 0, 0, 0);
var datee = diff / 1000 / 60 / 60 / 24;
document.cir.val4.value = datee + " days left for your next birthday";
}
}
function color(test) {
for (var j = 7; j < 12; j++) {
var myI = document.getElementsByTagName("input").item(j);
//myI.setAttribute("style",ch);
myI.style.backgroundColor = test;
}
}
function color1(test) {
var myI = document.getElementsByTagName("table").item(0);
//myI.setAttribute("style",ch);
myI.style.backgroundColor = test;
}
.cal-container {
width: 540px;
margin: 10px auto 0;
}
#age-calculator {
background: none repeat scroll 0 0 #DDDDDD;
border: 1px solid #BEBEBE;
padding-left: 20px;
}
.calc {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px 2px 2px 1px;
padding: 2px 30px 3px;
height: 27px;
}
.calc:active {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px;
}
<title>Age calculator </title>
<body onload="wr_document()">
<div class="cal-container">
<div id="calculator-container">
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%px;">
<tbody>
<tr>
<td valign="top">
<h1 style="padding-top: 10px;">
Age Calculator</h1>
<div class="descalign">
<span>Calculate your age in days, years, minutes, seconds. Know how many days are left for your next birthday.</span><br /><br />
</div>
<div id="age-calculator">
<table bgcolor="" border="0" cellpadding="0" cellspacing="4" style="width: 100%px;">
<tbody>
<tr>
<td colspan="2">
<table class="result" style="height: 100%px; width: 100%px;">
<tbody>
<tr>
<td>
<form name="cir">
<table cellpadding="3" cellspacing="0">
<tbody>
<tr>
<td colspan="2">
<br /> Today's Date is:
</td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" name="len11" onkeyup="checkday(this)" size="2" type="text" value="" /> Month -
<input class="innerc resform" name="len12" onkeyup="checkmon(this)" size="2" type="text" value="" /> Year -
<input class="innerc resform" name="len13" onkeyup="checkyear(this)" size="4" type="text" value="" />
<br />
<br />
</td>
</tr>
<tr>
<td colspan="2"> Enter Your Date of Birth : </td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" name="len21" onkeyup="checkday(this)" size="2" type="text" /> Month -
<input class="innerc resform" name="len22" onkeyup="checkmon(this)" size="2" type="text" /> Year -
<input class="innerc resform" name="len23" onkeyup="checkyear(this)" size="4" type="text" />
<br />
<br />
<input class="calc" name="but" onclick="calage()" type="button" value=" Go " />
<br />
<br />
</td>
</tr>
<tr>
<td align="center" class="form" width="30%">
<b> </b>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
<b> Your Age is </b>
</td>
<td>
<input class="resform" name="val" readonly="" size="36" type="text" />
</td>
</tr>
<tr>
<td>
<b> Your Age in Days </b>
</td>
<td>
<input class="resform" name="val1" readonly="" size="36" type="text" />
</td>
</tr>
<tr>
<td>
<b> Your Age in Hours </b>
</td>
<td>
<input class="resform" name="val2" readonly="" size="36" type="text" /> (Approximate)
</td>
</tr>
<tr>
<td class="form">
<b> Your Age in Minutes </b>
</td>
<td>
<input class="resform" name="val3" readonly="" size="36" type="text" /> (Approximate)
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td></td>
<td>
<input class="innerc resform" name="val4" readonly="" size="36" type="text" />
</td>
</tr>
</tbody>
</table>
</form>
</td>
</tr>
</tbody>
</table>
<br />
</td>
<td> </td>
</tr>
<tr>
<td align="right" colspan="2"> </td>
<td> </td>
</tr>
</tbody>
</table>
<br />
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
Not clear about purpose of your whole code, but based on your question following script may help you.
// Let below variables store your birth date
var day = 13;
var month = 03;
var year = 1993;
var x = 30; // Finding 30th birthday
var xthBirthday = new Date((year + x), (month - 1), day); // As month starts with 0
var timeForXthBirthday = xthBirthday.getTime() - Date.now();
var noOfDaysForXthBirthday = Math.ceil(timeForXthBirthday / (1000 * 60 * 60 * 24)); // No. of days left for your xth birthday
document.write(noOfDaysForXthBirthday+" days left for your "+x+"<sup>th</sup> birthday.");
Hope this helps.
<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
var grade = new Array(9);
var credit = new Array(9);
var getGrade = new Array(5);
var getCredit = new Array(5);
var gradeCount = 12;
grade[0] = "A+";
credit[0] = 4;
grade[1] = "A";
credit[1] = 4;
grade[2] = "A-";
credit[2] = 3.7;
grade[3] = "B+";
credit[3] = 3.3;
grade[4] = "B";
credit[4] = 3;
grade[5] = "B-";
credit[5] = 2.7;
grade[6] = "C+";
credit[6] = 2;
grade[7] = "C-";
credit[7] = 1.7;
grade[8] = "D+";
credit[8] = 1.3;
grade[9] = "D";
credit[9] = 1;
grade[10] = "D-";
credit[10] = 0.7;
grade[11] = "F";
credit[11] = 0.0;
getGrade[0] = document.calcGpaForm.grade1.value;
getGrade[0] = getGrade[0].toUpperCase();
getGrade[1] = document.calcGpaForm.grade2.value;
getGrade[1] = getGrade[1].toUpperCase();
getGrade[2] = document.calcGpaForm.grade3.value;
getGrade[2] = getGrade[2].toUpperCase();
getGrade[3] = document.calcGpaForm.grade4.value;
getGrade[3] = getGrade[3].toUpperCase();
getGrade[4] = document.calcGpaForm.grade5.value;
getGrade[4] = getGrade[4].toUpperCase();
getGrade[5] = document.calcGpaForm.grade6.value;
getGrade[5] = getGrade[5].toUpperCase();
getCredit[0] = document.calcGpaForm.credit1.value;
getCredit[1] = document.calcGpaForm.credit2.value;
getCredit[2] = document.calcGpaForm.credit3.value;
getCredit[3] = document.calcGpaForm.credit4.value;
getCredit[4] = document.calcGpaForm.credit5.value;
getCredit[5] = document.calcGpaForm.credit6.value;
var totalGrades =0;
var totalCredits = 0;
var GPA = 0;
var i = 0;
for (i; i < 6; i++) {
if (getGrade[i] == "") {
break;
}
else if (getGrade[i] == "c" || getGrade[i] == "C") {
alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
return;
}
else if (isNaN(getCredit[i])) {
alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
return;
}
else if (getCredit[i] == "") {
alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
return;
}
var validgradecheck = 0;
var x = 0;
for (x; x < gradeCount; x++) {
if (getGrade[i] == grade[x]) {
totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
totalCredits = totalCredits + parseInt(getCredit[i],10);
validgradecheck = 1;
break;
}
}
if (validgradecheck == 0) {
alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
return;
}
}
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
alert("GPA = " + eval(GPA));
return;
}
function copyRight() {
var lastModDate = document.lastModified;
var lastModDate = lastModDate.substring(0,10);
displayDateLast.innerHTML = "<h6>Copyright © Haiwook Choi. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
I'm trying to make a webpage that allows the user to enter from 4 to 6 grades for any course. Next to the letter grade, I'm wanting to put a text-field that accepts the credit hours for the courses. Also when the Calculate GPA button is clicked I want it to verify that a letter grade has been entered and then accumulate the grade points as well as the credit hours and display the GPA. I'm having trouble getting the GPA to calculate though. As well as having an alert display when a user enters anything other than a letter grade? Can someone look over my code and tell me what I should fix or add? Thanks if you read this and attempt to help!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter 10 Cases and Places: 2</title>
<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
var grade = new Array(9);
var credit = new Array(9);
var getGrade = new Array(5);
var getCredit = new Array(5);
var gradeCount = 12;
grade[0] = "A+";
credit[0] = 4;
grade[1] = "A";
credit[1] = 4;
grade[2] = "A-";
credit[2] = 3.7;
grade[3] = "B+";
credit[3] = 3.3;
grade[4] = "B";
credit[4] = 3;
grade[5] = "B-";
credit[5] = 2.7;
grade[6] = "C+";
credit[6] = 2;
grade[7] = "C-";
credit[7] = 1.7;
grade[8] = "D+";
credit[8] = 1.3;
grade[9] = "D";
credit[9] = 1;
grade[10] = "D-";
credit[10] = 0.7;
grade[11] = "F";
credit[11] = 0.0;
getGrade[0] = document.calcGpaForm.grade1.value;
getGrade[0] = getGrade[0].toUpperCase();
getGrade[1] = document.calcGpaForm.grade2.value;
getGrade[1] = getGrade[1].toUpperCase();
getGrade[2] = document.calcGpaForm.grade3.value;
getGrade[2] = getGrade[2].toUpperCase();
getGrade[3] = document.calcGpaForm.grade4.value;
getGrade[3] = getGrade[3].toUpperCase();
getGrade[4] = document.calcGpaForm.grade5.value;
getGrade[4] = getGrade[4].toUpperCase();
getGrade[5] = document.calcGpaForm.grade6.value;
getGrade[5] = getGrade[5].toUpperCase();
getCredit[0] = document.calcGpaForm.credit1.value;
getCredit[1] = document.calcGpaForm.credit2.value;
getCredit[2] = document.calcGpaForm.credit3.value;
getCredit[3] = document.calcGpaForm.credit4.value;
getCredit[4] = document.calcGpaForm.credit5.value;
getCredit[5] = document.calcGpaForm.credit6.value;
var totalGrades =0;
var totalCredits = 0;
var GPA = 0;
var i = 0;
for (i; i < 6; i++) {
if (getGrade[i] == "") {
break;
}
else if (getGrade[i] == "c" || getGrade[i] == "C") {
alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
return;
}
else if (isNaN(getCredit[i])) {
alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
return;
}
else if (getCredit[i] == "") {
alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
return;
}
var validgradecheck = 0;
var x = 0;
for (x; x < gradeCount; x++) {
if (getGrade[i] == grade[x]) {
totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
totalCredits = totalCredits + parseInt(getCredit[i],10);
validgradecheck = 1;
break;
}
}
if (validgradecheck == 0) {
alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
return;
}
}
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
alert("GPA = " + eval(GPA));
return;
}
function copyRight() {
var lastModDate = document.lastModified;
var lastModDate = lastModDate.substring(0,10);
displayDateLast.innerHTML = "<h6>Copyright © Hannah. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
</head>
<body onLoad="gpacalc(); copyRight()">
<div class="center-div">
<p style="font-family:Arial, Helvetica, sans-serif; font-size:xx-large; font-weight:bold; text-align: center; color:blue">Calculating Your GPA</p>
<p class="block"><strong>Directions: </strong>Enter your letter grade for your courses. In the boxes to the right enter the credit hours per course. Then Click the Calculate GPA button to have your GPA calculated as well as your total credit hours.</p>
<form name="calcGpaForm" method="post">
<table>
<tr>
<h4 style="text-align: center">Letter Grade:</h4>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 1:
</th>
<td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10" onBlur="validgradecheck" /></td>
<td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 2:
</th>
<td class="align-left"><input name="grade2" type="text" id="grade2" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit2" id="credit2" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 3:
</th>
<td class="align-left"><input name="grade3" type="text" id="grade3" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit3" id="credit3" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 4:
</th>
<td class="align-left"><input name="grade4" type="text" id="grade4" size="10" onBlur="validgradecheck" /> </td>
<td class="align-left"><input type="text" name="credit4" id="credit4" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 5:
</th>
<td class="align-left"><input type="text" name="grade5" id="grade5" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit5" id="credit5" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 6:
</th>
<td class="align-left"><input type="text" name="grade6" id="grade6" size="10" onBlur="validgradecheck"/></td>
<td class="align-left"><input type="text" name="credit6" id="credit6" size="10" /></td>
</tr>
<tr>
<td class="right-align">
<input name="button" type="button" value="Calculate GPA" onClick="gpacalc()"/>
</td>
<td class="align-left">
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">GPA:</span>
</td>
<td><input type="text" name="gpacalc" id="gpacalc" value=" " size="10" /></td>
</tr>
</table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
Few remarks:
I don't think you need to worry about old browsers as no one should be using them nowadays. Therefore, <!--Hide from old browsers --> not needed.
What's the point of calculating the GPA when the page loads i.e. onload? There are no grades when the page loads up, so you'll always get an error. It is probably better to only calculate when the user clicks the button.
Do not repeat yourself.
Do not write for yourself to only read but for others, so comment your code.
Check this answer on the difference between dot notation and square brack notation when it comes to accessing an object property.
eval() is evil and not needed in your code.
Here's how I would do it (hopefully it answers all your questions):
// an object is a better data structure for storing grading scale
var gradingScale = {
'A+': 4,
'A': 4,
'A-': 3.7,
'B+': 3.3,
'B': 3,
'B-': 2.7,
'C+': 2.3,
'C-': 1.7,
'D+': 1.3,
'D': 1,
'D-': 0.7,
'F': 0.0
};
// note in JS, you can reference an element by their ID
// attaching onclick event handler to your button with ID "gpacalc"
gpacalc.onclick = function() {
var totalGradePoints = 0;
var totalCredits = 0;
// easier to just start at 1
for (var i = 1; i <= 6; i++) {
// you can access an object's property using [] notation; useful in this situation
// good idea to normalize your values e.g. trim, uppercase, etc
var grade = document.calcGpaForm['grade' + i].value.trim().toUpperCase();
var credit = document.calcGpaForm['credit' + i].value.trim();
// skip if no grade is entered
if (grade == "") {
break;
}
// check if grade is invalid i.e. not in the grading scale
if (!gradingScale.hasOwnProperty(grade)) {
alert("'" + grade + "' is not a valid letter grade. Course " + i + ".");
return;
// check if credit is empty
} else if (credit == "") {
alert("You left the number of credits blank for Course " + i + ".");
return;
// check if credit is not a number
} else if (isNaN(credit)) {
alert("Enter a valid number of credits for Course " + i + ".");
return;
}
// at this point, the grade and credit should both be valid...
credit = parseInt(credit, 10);
// so let's add them to the tally
totalGradePoints += gradingScale[grade] * credit;
totalCredits += credit;
}
// check if total credits is greater than zero
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
// show total
gpa.value = Math.round((totalGradePoints / totalCredits) * 10) / 10;
}
<form name="calcGpaForm" method="post">
<table>
<tr>
<h4 style="text-align: center">Letter Grade:</h4>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 1:
</th>
<td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10"></td>
<td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 2:
</th>
<td class="align-left"><input name="grade2" type="text" id="grade2" size="10"></td>
<td class="align-left"><input type="text" name="credit2" id="credit2" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 3:
</th>
<td class="align-left"><input name="grade3" type="text" id="grade3" size="10"></td>
<td class="align-left"><input type="text" name="credit3" id="credit3" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 4:
</th>
<td class="align-left"><input name="grade4" type="text" id="grade4" size="10"></td>
<td class="align-left"><input type="text" name="credit4" id="credit4" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 5:
</th>
<td class="align-left"><input type="text" name="grade5" id="grade5" size="10"></td>
<td class="align-left"><input type="text" name="credit5" id="credit5" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 6:
</th>
<td class="align-left"><input type="text" name="grade6" id="grade6" size="10"></td>
<td class="align-left"><input type="text" name="credit6" id="credit6" size="10"></td>
</tr>
<tr>
<td class="right-align">
<input type="button" value="Calculate GPA" id="gpacalc">
</td>
<td class="align-left">
<input name="Reset" type="reset">
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">GPA:</span>
</td>
<td><input type="text" id="gpa" value="" size="10"></td>
</tr>
</table>
</form>
(Note: the sample attaches an onclick event handler to your button in the JS and not by using an onclick attribute. Though, the latter way should work.)
Good evening! I'm teaching myself to code. Right now, I'm making a JavaScript loan calculator, but I hit a snag. If I put 0% interest, it displays nothing in my output textboxes. Everything else is working perfectly though. Any help would be appreciated. Thanks!
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loan Calculator</title>
<style type="text/css">
.auto-style1 {
text-align: left;
}
.auto-style2 {
font-size: larger;
color: #FFF;
font: Georgia;
}
.auto-style3 {
width: 82px;
text-align: center;
style="float: right;
}
table {
background-color: #F5F5F5;
width: 400px;
height: 300px;
padding-left: 20px;
padding-bottom: 20px;
padding-top: 20px;
}
body {
background-color: #d2691e;
}
</style>
</head>
<body>
<form name="loaninfo">
<div class="auto-style1">
<p><strong>
<span class="auto-style2"> </span></strong><strong><span class="auto-style2"><br />
</span></strong></p>
</div>
<table width="327">
<tr><td colspan="3"></td></tr>
<tr>
<td>Loan Amount:</td>
<td>
$
<input type="text" name="principal" size="12" title="textfield" pattern="([0-9]+\.)?[0-9]+" >
</td>
</tr>
<tr>
<td>Interest Rate:</td>
<td>
<input type="text" name="interest" size="12" title="textfield" pattern="([0-9]+\.)?[0-9]+" >
%
</td>
</tr>
<tr>
<td>Number of Years for Loan:</td>
<td>
<input type="text" name="years" size="12" title="textfield" pattern="([0-9]+\.)?[0-9]+" >
</td>
</tr>
<tr>
<td colspan="3"><input type="button" class="auto-style3" onClick="calculate();" value="Calculate">
<br />
<br />
</td>
</tr>
<tr>
<td colspan="3">
<b>Your Payment Information</b>
</td>
</tr>
<tr>
<td>Monthly Payment Amount:</td>
<td>$ <input type="text" name="payment" size="12" readonly /></td>
</tr>
<tr>
<td>Total Payment Amount:</td>
<td>$ <input type="text" name="total" size="12" readonly ></td>
</tr>
<tr>
<td>Total Interest Payments:</td>
<td>$ <input type="text" name="totalinterest" size="12" readonly /> </td>
</tr>
<tr>
<td colspan="3">
<input type="reset" class="auto-style3" />
</td>
</tr>
</table>
</form>
<script language="JavaScript">
function calculate() {
var principal = document.loaninfo.principal.value;
var months_in_year = 12
var interest = document.loaninfo.interest.value / 100 / months_in_year;
var payments = document.loaninfo.years.value * months_in_year;
var x = Math.pow(1 + interest, payments);
var monthval = (principal*x*interest)/(x-1);
if (!isNaN(monthval) &&
(monthval != Number.POSITIVE_INFINITY) &&
(monthval != Number.NEGATIVE_INFINITY)) {
document.loaninfo.payment.value = round(monthval);
document.loaninfo.total.value = round(monthval * payments);
document.loaninfo.totalinterest.value = round((monthval * payments) - principal);
}
else {
document.loaninfo.payment.value = "";
document.loaninfo.total.value = "";
document.loaninfo.totalinterest.value = "";
}
function round(x) {
return Math.round(x*100)/100;
}
function jsDecimals(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
if (!jsIsUserFriendlyChar(key, "Decimals")) {
return false;
}
}
else {
if (evt.shiftKey) {
return false;
}
}
}
return true;
}
form.onsubmit = function () {
return textarea.value.match(/^\d+(\.\d+)?$/);
}
</script>
When you put 0 you are getting
var x = Math.pow(1 + interest, payments); // 1
var monthval = principal * x * interest / (x - 1); //NaN because 1-1 in fraction is 0 so it returns 0/0 and it's NaN
you can change you code to be like this:
if (interest===0){
var monthval = (principal)/(months_in_year);
} else {
var monthval = (principal*x*interest)/(x-1);
}
Working Version: http://codepen.io/mhadaily/pen/ZpypdA
feel free to change it to be like what you want.
It's because of this section of code.
else if (interest == 0) {
document.loaninfo.payment.value = "";
document.loaninfo.total.value = "";
document.loaninfo.totalinterest.value = "";
}
When the interest is 0, you are setting the values of all your output boxes to an empty string.
You should replace the RHS of the assignment.
I have an order form within an HTML table associated to some JavaScript verification logic. The current code works but I would like some enhancements to be implemented.
Currently, pressing the "verify" order button gives me the following output:
Line 0 = 1 Qty Line 1 = 4 Qty Line 2 = 2 Qty
Instead of showing table lines numbers followed by quantity value, I need the text to contain the actual products names. E.g. "Line 0 = 1" → "Apple = 1" …
I cannot really seem to figure it out can someone tell me how to do this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
<!-- Original: Mike McGrath (mike_mcgrath#example.net) -->
<!-- Web Site: http://website.example.net/~mike_mcgrath/ -->
<!--
function count(f, n, u) {
f.line_sum[n].value = f.line[n].value * u;
f.line_sum[n].value = Math.ceil(f.line_sum[n].value * 1000) / 1000;
f.line_sum[n].value = Math.floor(f.line_sum[n].value * 1000) / 1000;
f.line_sum[n].value = Math.round(f.line_sum[n].value * 100) / 100;
if (f.line_sum[n].value == "NaN") {
alert("Error:\nYou may only enter numbers...\nPlease retry");
f.line[n].value = f.line[n].value.substring(0, f.line[n].value.length - 1);
f.line_sum[n].value = f.line[n].value * u;
if (f.line_sum[n].value == "0") f.line_sum[n].value = "";
} else {
var gt = 0;
for (i = 0; i < f.line_sum.length; i++) {
gt += Math.ceil(f.line_sum[i].value * 1000) / 1000;
}
gt = Math.round(gt * 1000) / 1000;
f.grand_total.value = "$ " + gt;
decimal(f);
}
}
function get_data(f) {
var order_data = "This Order is ...\n";
for (i = 0; i < f.line.length; i++) {
if (f.line[i].value == "") f.line[i].value = "0";
order_data += "Line " + i + " = " + f.line[i].value + " Qty\n";
}
if (f.grand_total.value == "") f.grand_total.value = "Nil";
order_data += "Total Order Value = " + f.grand_total.value;
document.g.order.value = order_data;
}
function decimal(f) {
for (i = 0; i < f.line_sum.length; i++) {
var d = f.line_sum[i].value.indexOf(".");
if (d == -1 && f.line[i].value != 0) f.line_sum[i].value += ".00";
if (d == (f.line_sum[i].value.length - 2)) f.line_sum[i].value += "0";
if (f.line_sum[i].value == "00") f.line_sum[i].value = "";
}
d = f.grand_total.value.indexOf(".");
if (d == -1) f.grand_total.value += ".00";
if (d == (f.grand_total.value.length - 2)) f.grand_total.value += "0";
}
function send_data(g) {
get_data(document.f);
if (document.f.grand_total.value == "Nil") {
var conf = confirm("No items are entered - \nDo you want to submit a blank order?");
if (conf) g.submit();
else init();
} else g.submit();
}
function init() {
document.f.reset();
document.f.line[0].select();
document.f.line[0].focus();
document.g.order.value = "";
}
window.onload = init;
// -->
</SCRIPT>
</head>
<body>
<FORM NAME="f">
<TABLE BGCOLOR="mistyrose" BORDER="2" WIDTH="320" CELLPADDING="5" CELLSPACING="0" SUMMARY="">
<TBODY>
<TR>
<TD COLSPAN="4" ALIGN="center">
<B>Order Form</B>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>
<U>Item</U>
</TD>
<TD>
<U>Qty</U>
</TD>
<TD>
<U>Each</U>
</TD>
<TD ALIGN="right">
<U>Total</U>
</TD>
</TR>
<TR>
<TD>Apple</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,0,5.95)">
</TD>
<TD>$ 5.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>Banana</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,1,10.95)">
</TD>
<TD>$ 10.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR>
<TD>Orange</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,2,20.95)">
</TD>
<TD>$ 20.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>
<INPUT TYPE="button" VALUE="Reset" ONCLICK="init()">
</TD>
<TD COLSPAN="2" ALIGN="right">
<U>Grand Total :</U>
</TD>
<TD ALIGN="right">
<INPUT NAME="grand_total" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR>
<TD COLSPAN="4" ALIGN="center">
<INPUT TYPE="button" VALUE="Press to Verify Order" ONCLICK="get_data(this.form)">
</TD>
</TR>
</TBODY>
</TABLE>
</FORM>
<FORM NAME="g" METHOD="post" ENCTYPE="text/plain" ACTION="mailto:user#isp">
<TABLE BGCOLOR="cadetblue" BORDER="4" WIDTH="320" CELLPADDING="5" CELLSPACING="0" SUMMARY="">
<TBODY>
<TR>
<TD ALIGN="center">
<TEXTAREA NAME="order" ROWS="5" COLS="35">
</body>
</html>