How to get remaining days for certain birthday? - javascript

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.

Related

Calculating GPA and Credit Hours

<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.)

Calculating 0% Interest?

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.

auto calculate multiple dropdown selection

i am trying to generate total from dropdown selected values using html and JavaScript, my code is working. but when i an changing my choices from dropdown i want the total to be changed on every dropdown selection. But its not happening.
like if i am entering value in after tax income and selecting fortnightly in dropdown, the total changes. but when am entering second and third value and setting them monthly and weekly respectively, it doesnt change according to selection.
where could be the problem?
<script>
function asum() {
var first = document.getElementById('a1').value;
if (document.getElementById('a1').value == "") {
var first = 0;
}
var second = document.getElementById('a2').value;
if (document.getElementById('a2').value == "") {
var second = 0;
}
var third = document.getElementById('a3').value;
if (document.getElementById('a3').value == "") {
var third = 0;
}
var forth = document.getElementById('fc4').value;
if (document.getElementById('fc4').value == "") {
var forth = 0;
}
var fifth = document.getElementById('fc5').value;
if (document.getElementById('fc5').value == "") {
var fifth = 0;
}
var aresult = parseInt(first) + parseInt(second) + parseInt(third);
//aduration1
if (document.getElementById('aduration3').value == "Monthly") {
var aweekly = parseInt((aresult * 12) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = aweekly;
}
}
if (document.getElementById('aduration3').value == "Fortnightly") {
var weekly = parseInt((aresult * 26) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = weekly;
}
}
if (document.getElementById('aduration3').value == "Weekly") {
if (!isNaN(aresult)) {
document.getElementById('a4').value = parseInt(aresult);
}
}
//aduration2
if (document.getElementById('aduration2').value == "Monthly") {
var aweekly = parseInt((aresult * 12) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = aweekly;
}
}
if (document.getElementById('aduration2').value == "Fortnightly") {
var weekly = parseInt((aresult * 26) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = weekly;
}
}
if (document.getElementById('aduration2').value == "Weekly") {
if (!isNaN(aresult)) {
document.getElementById('a4').value = parseInt(aresult);
}
}
//aduration3
if (document.getElementById('aduration3').value == "Monthly") {
var aweekly = parseInt((aresult * 12) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = aweekly;
}
}
if (document.getElementById('aduration3').value == "Fortnightly") {
var weekly = parseInt((aresult * 26) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = weekly;
}
}
if (document.getElementById('aduration3').value == "Weekly") {
if (!isNaN(aresult)) {
document.getElementById('a4').value = parseInt(aresult);
}
}
}
</script>
<div>
<center>
<table cellpadding="5px" style="border: 1px solid !important; padding: 10px !important;width: 40% !important;">
<tr>
<td style="width: 25%;">
<label>After tax salary</label>
</td>
<td style="width: 20%;">
<input type="text" id="a1" placeholder="$" vlaue="0" onkeyup="asum();" />
</td>
<td style="width: 15%;">
<select id="aduration3" name="aduration3" onchange="asum();">
<option value="Monthly">Monthly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Weekly">Weekly</option>
</select>
</td>
<td style="width: 41%;">
</td>
</tr>
<tr>
<td>
<label>Net passive income</label>
</td>
<td>
<input type="text" id="a2" placeholder="$" onkeyup="asum();" />
</td>
<td>
<select id="aduration2" name="aduration2" onchange="asum();">
<option value="Monthly">Monthly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Weekly">Weekly</option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
<label>Other income</label>
</td>
<td>
<input type="text" id="a3" placeholder="$" onkeyup="asum();" />
</td>
<td>
<select id="aduration1" name="aduration1" onchange="asum();">
<option value="Monthly">Monthly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Weekly">Weekly</option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td colspan="2">
<input type="text" id="a4" placeholder="$" onclick="asum();" style="height: 30px !important; margin-top: 3px; margin-bottom: 3px;" />
</td>
<td>
<label><b style="font-size:16px;" onclick="asum();"><u>TOTAL WEEKLY INCOME</u></b>
<label>
</td>
</tr>
<tr>
<td>
</td>
<td colspan="2">
<input type="phone" id="a5" placeholder="$" onclick="bsum();" onkeyup="bsum();" style="height:30px !important;" />
</td>
<td>
<label><b style="font-size:16px;" onclick="bsum();"><u>TOTAL WEEKLY SURPLUS</u></b></label>
</td>
</tr>
</table>
</center>
</div>
You can do all of your calculation with few simple lines of code in jQuery:
$(':input').on('change blur keyup', function(){
var a = parseInt($('#a1').val()) || 0;
var b = parseInt($('#a2').val()) || 0;
var c = parseInt($('#a3').val()) || 0;
var aresult = a + b + c;
var ad2 = $('#aduration2').val();
var ad3 = $('#aduration3').val();
switch(ad2){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
switch(ad3){
case 'Monthly':
$('#a5').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a5').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a5').val( aresult );
break;
}
});
Fiddle HERE
PS in your code you mentioned #aduration1 which is not present in you're HTML, and your making double calculation for #aduration3
<code>
$(':input').on('change blur', function(){
var a = parseInt($('#a1').val()) || 0;
var b = parseInt($('#a2').val()) || 0;
var c = parseInt($('#a3').val()) || 0;
var aresult = a + b + c;
var ad1 = $('#aduration1').val();
var ad2 = $('#aduration2').val();
var ad3 = $('#aduration3').val();
switch(ad1){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
switch(ad2){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
switch(ad3){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
});

Jquery validation

I am new In jquery created validation and calculation using formula.I have created six input fields.created validation all fields.but when empty all fields click calculation red star symbol showing first two fields not showing remain four fields please help me friends
here my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1'
class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" />
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
calculation all working good.when leave fields empty click calculation show red star required first two column remain not showing help me friends
There is a mistake in the condition you have written for the valueC,valueD, valueE and valueF. You should continue as of valueA and valueA for the remaining too, if you want to achieve the functionality as you are trying to.
But, My Suggestion is to Use http://jqueryvalidation.org/ Plugin for validating the elements. It is very handy to use and customize as required.
Thank you
Check you conditions. small logical mistakes in your conditions. for eg.
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
This will check if either valuec or valued is empty. You are not checking for both empty. You need to add something like this
if (!valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
Brother its not a good trick to make your code lengthy. You could achieve your goal by using each function. Below is an example of doing that. Please have a look.
function validate(){
var formValidate = true;
jQuery(form + " select," + form + " input").each(
function (index) {
var input = jQuery(this);
if (input.val() == "" ) {
input.addClass("error");
input.parent().next("td").fadeIn("slow");
}
else {
input.removeClass("error");
input.parent().next("td").fadeOut("slow");
}
if (input.hasClass('error')) {
if (formValidate == true) {
formValidate = false;
}
}
}
);
if (formValidate == true) {
return true;
}
else {
return false;
}
}
exact solution to your answer is below please copy n paste then check.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../jQuery/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
//change is here
//change status value as per your requirement
if (!valueC && !valueD) {
//status = false;
$("#spand").show();
$("#spanc").show();
}
if (!valueE && !valueF) {
//status = false;
$("#spanf").show();
$("#spane").show();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" /></td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
If you really want to do it in that way consider below validation method.
I assume what you want is to check the input fields are empty or not. what you have done is still unclear to me.
To do a proper validation you need to identify and state what should be checked and how should they handled as well.
function validate() {
var status = false;
var valueA = $("#valuea").val();
var valueB = $("#valueb").val();
var valueC = $("#valuec").val();
var valueD = $("#valued").val();
var valueE = $("#valuee").val();
var valueF = $("#valuef").val();
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
$("#spanb").hide();
status = true;
}
else {
$("#spanb").show();
status = false;
}
if (valueC) {
$("#spanc").hide();
status = true;
}
else {
$("#spanc").show();
status = false;
}
if (valueD) {
$("#spand").hide();
status = true;
}
else {
$("#spand").show();
status = false;
}
if (valueE) {
$("#spane").hide();
status = true;
}
else {
$("#spane").show();
status = false;
}
if (valueF) {
$("#spanf").hide();
status = true;
}
else {
$("#spanf").show();
status = false;
}
return status;
}

calculate month and year between two dates javascript using jsp,display the value in duration textbox

<html>
<head>
<script language="javascript" type="text/javascript" src="datetimepicker_css.js"></script>
</head>
<body bgcolor="#c8c4c4">
<center>
<div id="content" style="background-color:#f1f1f1;height:auto;width: 80%;float: inside;">
<form class="demo" name="" method="post" action="connection.jsp">
<table align="center">
<tr>
<td>
<h2 align="center"><font style="font-weight: bold;size:10;">Employee Database</font></h2>
<table align="center" bgcolor="#f1f1f1" width="800" border="2" cellpadding="4" cellspacing="3">
<tr>
<th>From Date</th>
<th>To Date</th>
<th>Duration</th>
<tr>
<td>
<input type="text" name="fromdate" id="demo3" maxlength="20" style="float:left" size="14">
<img src="images2/cal.gif" onclick="javascript:NewCssCal('demo1', 'ddMMyyyy', 'dropdown', true, '12', true)" style="cursor:pointer;float:left;" />
</td>
<td>
<input type="text" name="to_date" id="demo3" maxlength="20" style="float:left" size="14">
<img src="images2/cal.gif" onclick="javascript:NewCssCal('demo1', 'ddMMyyyy', 'dropdown', true, '12', true)" style="cursor:pointer;float:left;" />
</td>
<td>
<input type="text" name="duration">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</div>
function caldur(val)
{
var d1 = new Date(document.getElementById("st").value); //from date yyyy-MM-dd
var d2 = new Date(document.getElementById("en").value); //to date yyyy-MM-dd (taken currentdate)
var Months = d2.getMonth() - d1.getMonth();
var Years = d2.getFullYear() - d1.getFullYear();
var Days = d2.getDate() - d1.getDate();
Months = (d2.getMonth() + 12 * d2.getFullYear()) - (d1.getMonth() + 12 * d1.getFullYear());
var MonthOverflow = 0;
if (Months - (Years * 12) < 0)
MonthOverFlow = -1;
else
MonthOverFlow = 1;
if (MonthOverFlow < 0)
Years = Years - 1; Months = Months - (Years * 12);
var LastDayOfMonth = new Date(d2.getFullYear(),
d2.getMonth() + 1, 0, 23, 59, 59);
LastDayOfMonth = LastDayOfMonth.getDate();
if (MonthOverFlow < 0 && (d1.getDate() > d2.getDate())) {
Days = LastDayOfMonth + (d2.getDate() - d1.getDate()) - 1;
}
else
Days = d2.getDate() - d1.getDate();
if (Days < 0)
Months = Months - 1;
var l = new Date(d2.getFullYear(), d2.getMonth(), 0);
var l1 = new Date(d1.getFullYear(), d1.getMonth() + 1, 0);
if (Days < 0)
{
if (l1 > l)
Days = l1.getDate() + Days;
else
Days = l.getDate() + Days;
}
if(Years<0 || Months<0 || Days<0)
{
alert("End date should be bigger than start date");
return;
}
document.getElementById("dr").value=Years + "Y(s), " + Months + " M(s), " + Days + "D(s)";
}
where st and en are the id's of text boxes contains start date and end date.

Categories