How do I use objects in JavaScript - javascript

I need help integrating classes and functions into an HTML page using JavaScript. I am not sure how to properly create an object and call its function(i.e.)
function calculateGrade(){
var x1 = document.forms["myForm"]["fname"].value;
var x2 = document.forms["myForm"]["lname"].value;
var x3 = document.forms["myForm"]["hwork"].value;
var x4 = document.forms["myForm"]["awork"].value;
var x5 = document.forms["myForm"]["midscore"].value;
var x6 = document.forms["myForm"]["midgrade"].value;
var x7 = document.forms["myForm"]["finscore"].value;
var x8 = document.forms["myForm"]["fingrade"].value;
var p1 = new Student(
x1,x2,[x3],[x4],x5,x6,x7,x8
); //creates it
document.getElementById("myForm").style.visibility="hidden";
document.getElementById("text").style.visibility="hidden";
alert(p1.getGrade()); //calls one of its methods
return false;
}
I am also unsure how to properly use classes in JS. I want the classes to be private while the methods are privileged.
function Student(){
function Student(firstName,lastName,hScore,aScore,mScore,mGrade,fScore,fGrade){
this.firstName = firstName;
this.lastName = lastName;
this.homework = new Coursework();
this.inClass = new Coursework();
this.studentsFinal = new Exam(fScore,fGrade);
this.studentsMidterm = new Exam(mScore,mGrade);
var that = this;
function setMidterm(mScore, mGrade){
that.studentsMidterm = new Exam(mScore, mGrade);
}
this.setMidterm = function() { // privileged method
setMidterm(mScore, mGrade);
}
function setFinal( fScore, fGrade){
that.studentsFinal = new Exam(fScore, fGrade);
}
this.setFinal = function() { // privileged method
setFinal( fScore, fGrade);
}
function addGradedHomework(hScore){
that.homework.addScore(hScore);
}
this.addGradedHomework = function() { // privileged method
addGradedHomework(hScore);
}
function addGradedActivity(aScore){
that.inClass.addScore(aScore);
}
this.addGradedActivity = function() { // privileged method
addGradedActivity(aScore);
}
this.printGrade=printGrade;
function getGrade(){
var letterGrade;
var weightCourse = ( (that.inClass.meanScore() * .15) + (that.homework.meanScore() * .25) + (that.studentsMidterm.getExamScore() * .25) + (that.studentsFinal.getExamScore() * .35) );
if (that.studentsMidterm.getExamScore() >= that.studentsFinal.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = studentsFinal.getExamGrade();
else if (that.studentsFinal.getExamScore() >= that.studentsMidterm.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = that.studentsFinal.getExamGrade();
else{
if (90.00 <= weightCourse){
letterGrade = "A";
}
else if( 80 <= weightCourse && weightCourse < 90){
letterGrade = "B";
}
else if (70 <= weightCourse && weightCourse < 80){
letterGrade = "C";
}
else if (60 <= weightCourse && weightCourse < 70){
letterGrade = "D";
}
else{
letterGrade = "F";
}
}
return letterGrade;
}
this.getGrade = function() { // privileged method
getGrade();
}
}
}
function Coursework(){
var sumScore;
var numScore;
function addScore(score){
numScore++;
if (score > 100)
sumScore = sumScore + 100;
else if ( score < 0)
sumScore = sumScore + 0;
else
sumScore = sumScore + score;
}
function meanScore(){
if (numScore == 0){
return 0.0;
}
else{
return (sumScore / numScore);
}
}
}
function Exam() {
var examScore;
var examGrade;
function Exam(score,grade ){
if (examScore < 0){
examScore = 0;
}
else if (examScore > 100){
examScore = 100;
}
else {
examScore = score;
}
switch (grade) {
case "A":
examGrade = "A";
break;
case "B":
examGrade = "B";
break;
case "C":
examGrade = "C";
break;
case "D":
examGrade = "D";
break;
case "F":
examGrade = "F";
break;
default:
examGrade = "F";
}
}
function getExamScore(){
return examScore;
}
function getExamGrade(){
return examGrade;
}
}
Any help is appreciated. If this does not make since let me know, I wasn't quite sure how to word it.
<html>
<title> Assignment 7 </title>
<h1> Students's Assignment 7 </h1>
<head>
<script type="text/javascript">
function calculateGrade(){
var x1 = document.forms["myForm"]["fname"].value;
var x2 = document.forms["myForm"]["lname"].value;
var x3 = document.forms["myForm"]["hwork"].value;
var x4 = document.forms["myForm"]["awork"].value;
var x5 = document.forms["myForm"]["midscore"].value;
var x6 = document.forms["myForm"]["midgrade"].value;
var x7 = document.forms["myForm"]["finscore"].value;
var x8 = document.forms["myForm"]["fingrade"].value;
var p1 = new Student(
x1,x2,[x3],[x4],x5,x6,x7,x8
);
//console.log(p1.getGrade());
//alert(x1);
document.getElementById("myForm").style.visibility="hidden";
document.getElementById("text").style.visibility="hidden";
alert(p1.getGrade());
return false;
}
function Student(){
function Student(firstName,lastName,hScore,aScore,mScore,mGrade,fScore,fGrade){
this.firstName = firstName;
this.lastName = lastName;
this.homework = new Coursework();
this.inClass = new Coursework();
this.studentsFinal = new Exam(fScore,fGrade);
this.studentsMidterm = new Exam(mScore,mGrade);
var that = this;
function setMidterm(mScore, mGrade){
that.studentsMidterm = new Exam(mScore, mGrade);
}
this.setMidterm = function() { // privileged method
setMidterm(mScore, mGrade);
}
function setFinal( fScore, fGrade){
that.studentsFinal = new Exam(fScore, fGrade);
}
this.setFinal = function() { // privileged method
setFinal( fScore, fGrade);
}
function addGradedHomework(hScore){
that.homework.addScore(hScore);
}
this.addGradedHomework = function() { // privileged method
addGradedHomework(hScore);
}
function addGradedActivity(aScore){
that.inClass.addScore(aScore);
}
this.addGradedActivity = function() { // privileged method
addGradedActivity(aScore);
}
this.printGrade=printGrade;
function getGrade(){
var letterGrade;
var weightCourse = ( (that.inClass.meanScore() * .15) + (that.homework.meanScore() * .25) + (that.studentsMidterm.getExamScore() * .25) + (that.studentsFinal.getExamScore() * .35) );
if (that.studentsMidterm.getExamScore() >= that.studentsFinal.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = studentsFinal.getExamGrade();
else if (that.studentsFinal.getExamScore() >= that.studentsMidterm.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = that.studentsFinal.getExamGrade();
else{
if (90.00 <= weightCourse){
letterGrade = "A";
}
else if( 80 <= weightCourse && weightCourse < 90){
letterGrade = "B";
}
else if (70 <= weightCourse && weightCourse < 80){
letterGrade = "C";
}
else if (60 <= weightCourse && weightCourse < 70){
letterGrade = "D";
}
else{
letterGrade = "F";
}
}
return letterGrade;
}
this.getGrade = function() { // privileged method
getGrade();
}
}
}
function Coursework(){
var sumScore;
var numScore;
function addScore(score){
numScore++;
if (score > 100)
sumScore = sumScore + 100;
else if ( score < 0)
sumScore = sumScore + 0;
else
sumScore = sumScore + score;
}
function meanScore(){
if (numScore == 0){
return 0.0;
}
else{
return (sumScore / numScore);
}
}
}
function Exam() {
var examScore;
var examGrade;
function Exam(score,grade ){
if (examScore < 0){
examScore = 0;
}
else if (examScore > 100){
examScore = 100;
}
else {
examScore = score;
}
switch (grade) {
case "A":
examGrade = "A";
break;
case "B":
examGrade = "B";
break;
case "C":
examGrade = "C";
break;
case "D":
examGrade = "D";
break;
case "F":
examGrade = "F";
break;
default:
examGrade = "F";
}
}
function getExamScore(){
return examScore;
}
function getExamGrade(){
return examGrade;
}
}
</script>
</head>
<body bgcolor="#81F79F">
<b id="text">Enter you information below</b>
<form id="myForm" onsubmit="return calculateGrade();" >
First name: <br><input type="text" id="element_1_1" name="fname"><br>
Last name: <br><input type="text" id="element_1_2" name="lname"><br>
Homework: <br><input type="text" id="element_1_3" name="hwork"><br>
Activity: <br><input type="text" id="element_1_4" name="awork"><br>
Midterm Score: <br><input type="text" id="element_1_5" name="midscore"><br>
Midterm Grade: <br><input type="text" id="element_1_6" name="midgrade"><br>
Final Score: <br><input type="text" id="element_1_7" name="finscore"><br>
Final Grade: <br><input type="text" id="element_1_8" name="fingrade"><br>
<input type="submit" value="Submit">
</form>
<div id="stuff"></div>
</body>
</html>

Related

how to call methods inside the constructor in a calss

Hello I am trying to solve an exercise where we have to create a class Appliance and then two child classes (tv and washing machine), then I need to check the color and the consumption of the appliance, or their childs, and if none is passed it will be given a default value with a method. So far this is what I have but it keeps telling me this.checkcolor is not a function; I have tried the syntax also like this.color = checkColor(color) and also with constant giving the default values but nothing seems to work.
What would it be the easiest way to do this? Thanks
function Appliance(color, consumption, weight){
this.color = this.checkColor(color);
this.consumption = this.checkConsumption(consumption);
this.weight = weight || 5;
this.price = this.getPrice(this.consumption, this.weight);
Appliance.prototype.checkConsumption = function(consumption){
let res = "";
const consumptions = ["A", "B", "C", "D", "E", "F"];
for(let i = 0; i < consumptions; i++){
if(consumptions[i] == consumption){
res = consumption;
}
else{
res = "F";
}
}
return res
}
Appliance.prototype.checkColor = function(color){
let res = "";
let checker = false;
const colors = ["white", "red", "blue", "grey"];
for(let i = 0; i < colors.length && !checker; i++){
if(colors[i] == color){
checker = true;
}
}
if(checker){
res = color;
}
else{
res = "white";
}
return res;
}
Appliance.prototype.getPrice = function(consumption, weight){
let defaultPrice = 100;
let extra = 0;
switch(consumption){
case "A":
extra += 100;
break;
case "B":
extra += 80;
break;
case "C":
extra += 60;
break;
case "D":
extra += 50;
break;
case "E":
extra += 30;
break;
case "F":
extra += 10;
break;
}
if(weight >= 0 && weight < 19){
extra += 10;
}else if(weight >= 20 && weight < 49){
extra += 50;
}else if(weight >= 50 && weight <= 79){
extra += 80;
}else if(weight >= 80){
extra += 100;
}
return defaultPrice + extra;
}
Appliance.prototype.getColor = function(){
return this.color;
}
Appliance.prototype.getConsumption = function(){
return this.consumption;
}
Appliance.prototype.getWeight = function(){
return this.weight;
}
} ```

JS Calculator not working in wordpress, script worked on old site

This issue has been problematic this week. We're creating a new site as the current one is a bit outdated. The current site has a series of financial calculators that work perfectly.
Upon transferring the scripts and content to the new wordpress site, we get an error which prevents it from working.
The error we get is:
TypeError: document.formc is undefined[Learn More] accounting-calc.js:7:3
recalc_onclick
http://77.104.171.166/~paramo48/grtglobal.com/wp-content/themes/child-theme/js/accounting-calc.js:7:3
onclick
http://77.104.171.166/~paramo48/grtglobal.com/business-financial-calculators/:1:1
The script we use is:
/* <![CDATA[ */
var co = new Object;
function recalc_onclick(ctl) {
if (ctl == '') {
co.pA1B = eeparseFloatTh(document.formc.pA1B.value);
co.pA2B = eeparsePercent(document.formc.pA2B.value);
co.pA3B = eeparseFloat(document.formc.pA3B.value);
calc(co);
document.formc.pA4B.value = eedatefmt(fmtdate5, co.pA4B);
document.formc.pA5B.value = eedatefmt(fmtdate5, co.pA5B);
};
};
var eeisus = 0;
var eetrue = "TRUE";
var eefalse = "FALSE";
var eedec = ".";
var eeth = ",";
var eedecreg = new RegExp("[.]", "g");
var eethreg = new RegExp(",", "g");
var fmtdaynamesshort = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var fmtdaynameslong = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var fmtmonthnamesshort = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var fmtmonthnameslong = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var fmtstrings = new Array(",", " ", "");
var fmtdate5 = new Array(34, 25, 2);
var fmtdate6 = new Array(34, 25, 0);
function calc(data) {
var cA1B = data.pA1B;
var cA2B = data.pA2B;
var cA3B = data.pA3B;
var cA4B = (((pmt((((cA2B) / (12))), (((cA3B) * (12))), (cA1B), (0), (0))) * (-1)));
var cA5B = (((((cA1B) * (cA2B))) / (12)));
data.pA4B = cA4B;
data.pA5B = cA5B;
};
function myIsNaN(x) {
return (isNaN(x) || (typeof x == 'number' && !isFinite(x)));
};
function mod(n, d) {
return n - d * Math.floor(n / d);
};
function round(n, nd) {
if (isFinite(n) && isFinite(nd)) {
var sign_n = (n < 0) ? -1 : 1;
var abs_n = Math.abs(n);
var factor = Math.pow(10, nd);
return sign_n * Math.round(abs_n * factor) / factor;
} else {
return NaN;
}
};
function eeparseFloat(str) {
str = String(str).replace(eedecreg, ".");
var res = parseFloat(str);
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eeparsePercent(str) {
var parts = String(str).split('%');
var tmp = String(parts[0]).replace(eedecreg, ".");
var res = parseFloat(tmp) / 100;
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eedisplayFloat(x) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return String(x).replace(/\./g, eedec);
}
};
function eedisplayScientific(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var str = String(x.toExponential(nd));
return str.replace(/\./g, eedec);
}
};
function eedisplayFloatND(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var res = round(x, nd);
if (nd > 0) {
var str = String(res);
if (str.indexOf('e') != -1) return str;
if (str.indexOf('E') != -1) return str;
var parts = str.split('.');
if (parts.length < 2) {
var decimals = ('00000000000000').substring(0, nd);
return (parts[0]).toString() + eedec + decimals;
} else {
var decimals = ((parts[1]).toString() + '00000000000000').substring(0, nd);
return (parts[0]).toString() + eedec + decimals;
}
} else {
return res;
}
}
};
function eedisplayPercent(x) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var tmp = (x * 100).toString() + '%';
return tmp.replace(/\./g, eedec);
}
};
function eedisplayPercentND(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return eedisplayFloatND(x * 100, nd) + '%';
}
}
function eeparseFloatTh(str) {
str = String(str).replace(eethreg, "");
str = String(str).replace(eedecreg, ".");
var res = parseFloat(str);
if (isNaN(res)) {
return 0;
} else {
return res;
}
};
function eedisplayFloatNDTh(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
var res = round(x, nd);
if (nd > 0) {
var str = String(res);
if (str.indexOf('e') != -1) return str;
if (str.indexOf('E') != -1) return str;
var parts = str.split('.');
var res2 = eeinsertThousand(parts[0].toString());
if (parts.length < 2) {
var decimals = ('00000000000000').substring(0, nd);
return (res2 + eedec + decimals);
} else {
var decimals = ((parts[1]).toString() + '00000000000000').substring(0, nd);
return (res2 + eedec + decimals);
}
} else {
return (eeinsertThousand(res.toString()));
}
}
};
function eedisplayPercentNDTh(x, nd) {
if (myIsNaN(x)) {
return Number.NaN;
} else {
return eedisplayFloatNDTh(x * 100, nd) + '%';
}
}
function eeinsertThousand(whole) {
if (whole == "" || whole.indexOf("e") >= 0) {
return whole;
} else {
var minus_sign = "";
if (whole.charAt(0) == "-") {
minus_sign = "-";
whole = whole.substring(1);
};
var res = "";
var str_length = whole.length - 1;
for (var ii = 0; ii <= str_length; ii++) {
if (ii > 0 && ii % 3 == 0) {
res = eeth + res;
};
res = whole.charAt(str_length - ii) + res;
};
return minus_sign + res;
}
};
function eedatefmt(fmt, x) {
if (!isFinite(x)) return Number.NaN;
var tmp = 0;
var res = "";
var len = fmt.length;
for (var ii = 0; ii < len; ii++) {
if (fmt[ii] > 31) {
res += fmtstrings[fmt[ii] - 32];
} else {
switch (fmt[ii]) {
case 2:
res += eemonth(x);
break;
case 3:
tmp = eemonth(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 4:
res += fmtmonthnamesshort[eemonth(x) - 1];
break;
case 5:
res += fmtmonthnameslong[eemonth(x) - 1];
break;
case 6:
res += eeday(x);
break;
case 7:
tmp = eeday(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 8:
res += fmtdaynamesshort[weekday(x, 1) - 1];
break;
case 9:
res += fmtdaynameslong[weekday(x, 1) - 1];
break;
case 10:
tmp = year(x) % 100;
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 11:
res += year(x);
break;
case 12:
res += hour(x);
break;
case 13:
tmp = hour(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 14:
tmp = hour(x) % 12;
if (tmp == 0) {
res += "12";
} else {
res += tmp % 12;
};
break;
case 15:
tmp = hour(x) % 12;
if (tmp == 0) {
res += "12";
} else {
if (tmp < 10) {
res += "0";
};
res += tmp;
};
break;
case 16:
res += minute(x);
break;
case 17:
tmp = minute(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 18:
res += second(x);
break;
case 19:
tmp = second(x);
if (tmp < 10) {
res += "0";
};
res += tmp;
break;
case 21:
case 22:
if (hour(x) < 12) {
res += "AM";
} else {
res += "PM";
};
break;
case 23:
res += eedisplayFloat(x);
break;
case 24:
tmp = fmt[++ii];
res += eedisplayFloatND(x, tmp);
break;
case 25:
tmp = fmt[++ii];
res += eedisplayFloatNDTh(x, tmp);
break;
case 26:
res += eedisplayPercent(x);
break;
case 27:
tmp = fmt[++ii];
res += eedisplayPercentND(x, tmp);
break;
case 28:
tmp = fmt[++ii];
res += eedisplayPercentNDTh(x, tmp);
break;
case 29:
tmp = fmt[++ii];
res += eedisplayScientific(x, tmp);
break;
};
};
};
return res;
};
function leap_gregorian(year) {
return ((year % 4) == 0) && (!(((year % 100) == 0) && ((year % 400) != 0)));
}
var GREGORIAN_EPOCH = 1721425;
function gregorian_to_jd(year, month, day) {
return (GREGORIAN_EPOCH - 0) + (365 * (year - 1)) + Math.floor((year - 1) / 4) + (-Math.floor((year - 1) / 100)) + Math.floor((year - 1) / 400) + Math.floor((((367 * month) - 362) / 12) + ((month <= 2) ? 0 : (leap_gregorian(year) ? -1 : -2)) + day);
}
function jd_to_gregorian(jd) {
var wjd, depoch, quadricent, dqc, cent, dcent, quad, dquad, yindex, year, yearday, leapadj;
wjd = Math.floor(jd);
depoch = wjd - GREGORIAN_EPOCH - 1;
quadricent = Math.floor(depoch / 146097);
dqc = mod(depoch, 146097);
cent = Math.floor(dqc / 36524);
dcent = mod(dqc, 36524);
quad = Math.floor(dcent / 1461);
dquad = mod(dcent, 1461);
yindex = Math.floor(dquad / 365);
year = (quadricent * 400) + (cent * 100) + (quad * 4) + yindex;
if (!((cent == 4) || (yindex == 4))) {
year++;
}
yearday = wjd - gregorian_to_jd(year, 1, 1);
leapadj = ((wjd < gregorian_to_jd(year, 3, 1)) ? 0 : (leap_gregorian(year) ? 1 : 2));
var month = Math.floor((((yearday + leapadj) * 12) + 373) / 367);
var day = (wjd - gregorian_to_jd(year, month, 1)) + 1;
return new Array(year, month, day);
}
function eeday(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 0;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[2];
};
function hour(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return Math.floor(res / 3600);
}
function minute(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return Math.floor(res / 60) % 60;
};
function eemonth(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 1;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[1];
};
function second(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
var res = Math.floor((serial_number - Math.floor(serial_number)) * 86400 + 0.5);
return res % 60;
};
function weekday(serial_number, return_type) {
if (!isFinite(return_type) || !isFinite(serial_number)) return Number.NaN;
if (return_type < 1 || return_type > 3) return Number.NaN;
var res = Math.floor(serial_number + 6) % 7;
switch (Math.floor(return_type)) {
case 1:
return res + 1;
case 2:
return (res + 6) % 7 + 1;
case 3:
return (res + 6) % 7;
};
return "hej";
};
function year(serial_number) {
if (!isFinite(serial_number)) return Number.NaN;
if (serial_number < 1) {
return 1900;
}
if (serial_number > 60) serial_number--;
var res = jd_to_gregorian(serial_number + 2415020);
return res[0];
};
function pmt(rate, nper, pv, fv, type) {
if (rate == 0) {
return -pv / nper;
} else {
var pvif = Math.pow(1 + rate, nper);
var fvifa = (Math.pow(1 + rate, nper) - 1) / rate;
var type1 = (type != 0) ? 1 : 0;
return ((-pv * pvif - fv) / ((1 + rate * type1) * fvifa));
}
};
/* ]]> */
and the content is:
<form id="formc" method="post" action="" class="calc normal">
<noscript><p>Your browser does not support Javascript or has Javascript disabled.<br />Our calculators will not work without it.</p><p>If you want to enable Javascript but are unsure of how to do it, visit our website help page</p></noscript>
<p>See how much you can afford to borrow...</p>
<fieldset><legend><strong>Calculator</strong></legend>
<p><label for="pA1B">Amount of loan</label><span>£</span><input name="pA1B" id="pA1B" onblur="this.value=eedisplayFloatNDTh(eeparseFloatTh(this.value),0);recalc_onclick('pA1B')" value="" type="text"></p>
<p><label for="pA2B">Interest rate</label><span>%</span><input name="pA2B" id="pA2B" onblur="this.value=eedisplayPercentND(eeparsePercent(this.value),2);recalc_onclick('pA2B')" value="" type="text"></p>
<p><label for="pA3B">Term in years</label><span> </span><input name="pA3B" id="pA3B" onblur="this.value=eedisplayFloat(eeparseFloat(this.value));recalc_onclick('pA3B')" value="" type="text"></p>
<p class="formresult"><label for="pA4B">Monthly payment</label><span>£</span><input name="pA4B" tabindex="-1" id="pA4B" value="Result" readonly="readonly" type="text"></p>
<p class="formresult"><label for="pA5B">Interest only</label><span>£</span><input name="pA5B" tabindex="-1" id="pA5B" value="Result" readonly="readonly" type="text"></p>
<p><button type="button" name="xl_update_bottom" onclick="recalc_onclick('')">Calculate</button><button type="button" name="xl_reset_bottom" onclick="reset_onclick('')">Reset</button></p>
</fieldset>
<script>
/* <![CDATA[ */
function reset_onclick(x){document.formc.reset();postcode();recalc_onclick('');};function postcode(){};function eequerystring(){var querystring=document.location.search;if(querystring.length>0){variables=(querystring.substring(1)).split("&");var variable;var key;var value;for(var ii=0;ii<variables.length;ii++){variable=variables[ii].split("=");key=unescape(variable[0]);value=unescape(variable[1]);if(document.formc[key]!=null){document.formc[key].value=value;}}}}function initial_update(){postcode('');eequerystring();recalc_onclick('');}
/* ]]> */</script>
</form>
I'm sure it's something simple but I've yet to solve it.
At first I thought formc was a typo but it's the exact same on the original site where it works.
You are missing the name attribute on the form.
console.log(document.formc)
<form id="formc" name="formc">
</form>

How to interrupt my loop calling a function, calling an eventListener calling a function

I've made a meteor "game". On window load I set my shield:
window.onload = function() {
document.getElementById("shield").innerHTML = "Max";
var playStart = document.getElementById("playBtn");
playStart.addEventListener("click", playGame);
}
On a click of the play button I'm calling a function (playGame) to loop (currently 20 odd times). In this loop I call my meteor create function (called setUp):
function playGame() {
for (i = 0; i < 21; i++) {
if (document.getElementById("shield").innerHTML != "End") {
setUp();
} else {
continue;
}
}
}
In setup I create the meteor and animate it. I've added an event listener so that on the animation's end (i.e. the "player" hasn't destroyed the meteor) it calls a function to remove the meteor and change the shield status:
function setup() {
imgMeteor.addEventListener("animationend", imgEnd);
// This function (imgEnd is within my setUp function).
function imgEnd() {
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
var currShield = document.getElementById("shield").innerHTML;
switch (currShield) {
case "Max":
currShield = "Med";
break;
case "Med":
currShield = "Min";
break;
case "Min":
currShield = "None";
break;
case "None":
currShield = "End";
break;
}
document.getElementById("shield").innerHTML = currShield;
if (currShield == "End") {
return;
}
}
}
(I've tried to show just the relevant code). How can I stop the loop running. (Basically I want the game to end once the barrier is "End"?
Any help would be awesome. Entire code below if that helps.
var numText = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine"
];
var modText = ["0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"];
window.onload = function() {
document.getElementById("shield").innerHTML = "Max";
var arrNum = 0;
document.getElementById("spdText").innerHTML = numText[arrNum];
myNum = arrNum;
var upSpd = document.getElementById("upBtn");
upSpd.addEventListener("click", nextyNum);
var downSpd = document.getElementById("downBtn");
downSpd.addEventListener("click", prevyNum);
var playStart = document.getElementById("playBtn");
playStart.addEventListener("click", playGame);
var playPause = document.getElementById("pauseBtn");
playPause.addEventListener("click", pauseGame);
}
function nextyNum() {
myNum += 1;
if (myNum <= 9) {
document.getElementById("spdText").innerHTML = numText[myNum];
document.getElementById("warpProg").value = [myNum];
document.getElementById("currMod").innerHTML = modText[myNum]
} else {
alert("She cannie take any more cap'n. Speed's at maximum");
}
if (myNum > 9) {
myNum = 9;
}
progColourCheck();
}
function prevyNum() {
myNum -= 1;
if (myNum >= 0) {
document.getElementById("spdText").innerHTML = numText[myNum];
document.getElementById("warpProg").value = [myNum];
document.getElementById("currMod").innerHTML = modText[myNum];
} else {
alert("She's as low as she can go cap'n ");
}
if (myNum < 0) {
myNum = 0;
}
progColourCheck();
}
function progColourCheck() {
var progColours = ["lightgrey", "lightyellow", "yellow", "greenyellow", "lawngreen", "#73e600",
"#cc9900", "orange", "orangered", "red"
];
document.getElementById("warpProg").style.color = progColours[myNum];
document.getElementById("currMod").style.backgroundColor = progColours[myNum];
}
function playGame() {
var tempScore = document.getElementById(currScore);
tempScore = parseInt(currScore.innerHTML);
var hiScore = document.getElementById(hScore);
hiScore = parseInt(hScore.innerHTML);
if (tempScore > hiScore) {
hScore.innerHTML = tempScore;
}
currScore.innerHTML = 0000;
if (myNum == 0) {
alert("The ship's not movin' cap'n");
return;
}
for (i = 0; i < 21; i++) {
if (document.getElementById("shield").innerHTML != "End") {
document.getElementById("upBtn").disabled = "true";
document.getElementById("downBtn").disabled = "true";
setUp();
} else {
continue;
}
}
document.getElementById("titleText").style.visibility = "hidden";
document.getElementById("playBtn").style.visibility = "hidden";
}
function setUp() {
var imgMeteor = document.createElement("p");
var blankNode = document.createTextNode("");
imgMeteor.appendChild(blankNode);
document.getElementById("canvas").appendChild(imgMeteor);
imgMeteor.style.visibility = "hidden";
imgMeteor.style.backgroundImage = 'url("meteor.gif")';
imgMeteor.style.width = "56px";
imgMeteor.style.height = "56px";
imgMeteor.style.position = "absolute";
imgMeteor.addEventListener("mouseover", removeElement);
imgMeteor.style.animationName = "animBlock";
imgMeteor.style.animationDuration = 10 - myNum + "s";
imgMeteor.style.animationDelay = Math.floor(Math.random() * (8 - 0 + 1)) + 0 + "s";
imgMeteor.style.animationTimingFunction = "linear";
imgMeteor.addEventListener("animationstart", imgVis);
function imgVis() {
imgMeteor.style.visibility = "visible";
}
imgMeteor.addEventListener("animationend", imgEnd);
var leftPos = xPosition(0);
imgMeteor.style.left = leftPos + "%";
var topPos = yPosition(0);
imgMeteor.style.top = topPos + "px";
function removeElement() {
var cScore = document.getElementById("CurrScore");
cScore = parseInt(currScore.innerHTML);
cScore += (1 * myNum);
currScore.innerHTML = cScore;
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
document.getElementById("barrier").style.background = "linear-gradient(darkblue, lightblue)";
}
function imgEnd() {
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
document.getElementById("barrier").style.background = "linear-gradient(red, orange)";
var cScore = document.getElementById("CurrScore");
cScore = parseInt(currScore.innerHTML);
var negScore = myNum;
if (negScore > 1) {
negScore -= 1;
}
cScore -= (1 * negScore);
currScore.innerHTML = cScore;
var currShield = document.getElementById("shield").innerHTML;
switch (currShield) {
case "Max":
currShield = "Med";
break;
case "Med":
currShield = "Min";
break;
case "Min":
currShield = "None";
document.getElementById("bubble").style.visibility = "hidden";
break;
case "None":
currShield = "End";
break;
}
document.getElementById("shield").innerHTML = currShield;
if (currShield == "End") {
return;
}
}
}
function xPosition(lPos) {
var lPos = Math.floor(Math.random() * (90 - 1 + 1)) + 1;
return lPos;
}
function yPosition(tPos) {
var tPos = Math.floor(Math.random() * (80 - 10 + 1)) + 10;
return tPos;
}
function pauseGame() {
playBtn.style.visibility = "visible";
document.getElementById("upBtn").disabled = "false";
document.getElementById("downBtn").disabled = "false";
document.getElementById("shield").innerHTML = "Max";
}
Your loop should look like this then:
function playGame() {
for (i=0; i < 21; i++) {
if (document.getElementById("shield").innerHTML == "End"){
break;
}
SetUp();
}
}
You want to break the loop when the condition is met.

Jquery result display issue

I am trying to create a bmi calculator and tried the following .
$(document).ready(function() {
// Convert ft to inches
function convertHeight(ft) {
return ft * 12;
}
// calculate total height
function showbmi() {
var weight = document.getElementById('weight').value * 1;
var height_ft = document.getElementById('height_ft').value * 1;
var height_in = document.getElementById('height_in').value * 1;
var height = convertHeight(height_ft) + height_in;
var female_h = (height * height) / 30;
var male_h = (height * height) / 28;
var gender;
var x = document.getElementsByName("gender");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
gender = x[i].value;
break;
}
}
var bmi = "?";
if (gender == "female") {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
} else {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
}
var bmi_msg = "?";
if (bmi < 15) {
bmi_msg = "Very severely underweight";
} else if (bmi <= 16) {
bmi_msg = "Severely underweight";
} else if (bmi <= 18.4) {
bmi_msg = "Underweight";
} else if (bmi <= 24.9) {
bmi_msg = "Normal";
} else if (bmi <= 29.9) {
bmi_msg = "Overweight";
} else if (bmi <= 34.9) {
bmi_msg = "Obese Class I (Moderately obese)";
} else if (bmi <= 39.9) {
bmi_msg = "Obese Class II (Severely obese)";
} else {
bmi_msg = "Obese Class III (Very severely obese)";
}
$("#result").text(bmi);
return bmi;
$("#comment").text(bmi_msg);
return bmi_msg;
}
//bmi infos
//finish
$("form#calc input").bind("keydown", function() {
setTimeout(function() {
showbmi();
}, 100);
return true;
});
$("form#calc input").bind("change", function() {
showbmi();
});
$("form#calc radio").bind("change", function() {
showbmi();
});
$("form#calc").bind("submit", function() {
showbmi();
return false;
});
});
The bmi displays correctly, but the messages forbmi values are not displaying. i checked the console and it says code unreachable.
Can somebody throw some light where I am goin wrong, and How I can improve this code.
You have a return statement after setting the result content before setting the comment, so $("#comment").text(bmi_msg); is never executed.
A function will return control to the caller method as soon as a return statement is executed, so there should be only one return statement in an execution flow.
So remove return bmi; from the code for the comment setting to work
$(document).ready(function() {
// Convert ft to inches
function convertHeight(ft) {
return ft * 12;
}
// calculate total height
function showbmi() {
var weight = $('#weight').val() * 1;
var height_ft = $('#height_ft').val() * 1;
var height_in = $('#height_in').val() * 1;
var height = convertHeight(height_ft) + height_in;
var female_h = (height * height) / 30;
var male_h = (height * height) / 28;
var gender = $('input[name="gender"]:checked').val();
var bmi = "?";
if (gender == "female") {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
} else {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
}
var bmi_msg = "?";
if (bmi < 15) {
bmi_msg = "Very severely underweight";
} else if (bmi <= 16) {
bmi_msg = "Severely underweight";
} else if (bmi <= 18.4) {
bmi_msg = "Underweight";
} else if (bmi <= 24.9) {
bmi_msg = "Normal";
} else if (bmi <= 29.9) {
bmi_msg = "Overweight";
} else if (bmi <= 34.9) {
bmi_msg = "Obese Class I (Moderately obese)";
} else if (bmi <= 39.9) {
bmi_msg = "Obese Class II (Severely obese)";
} else {
bmi_msg = "Obese Class III (Very severely obese)";
}
$("#result").text(bmi);
$("#comment").text(bmi_msg);
return bmi;
}
//bmi infos
var timer;
$("#calc input").bind("keydown change", function() {
clearTimeout(timer);
timer = setTimeout(function() {
showbmi();
}, 100);
return true;
});
$("#calc").bind("submit", function() {
clearTimeout(timer);
showbmi();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="calc">
<input id="weight" />
<input id="height_ft" />
<input id="height_in" />
<br />
<input name="gender" type="radio" value="male" />
<input name="gender" type="radio" value="female" />
<br />
<input type="submit" value="Check" />
<div id="result"></div>
<div id="comment"></div>
</form>
Note: Since you are using jQuery, why not use its utility methods to get/set the values/content

Adding price to total when checkbox is selected

I would like to add a $5.00 charge whenever the txtBwayEDUGift checkbox is selected. The javascript code I currently have is reducing the amount when checkbox is unchecked, but not applying the charge when selected. I can provide additonal code if needed.
Here is my input type from my aspx page:
<input type="checkbox" name="txtBwayEDUGift" id="txtBwayEDUGift" onchange="checkboxAdd(this);" checked="checked" />
Here is my javascript:
{
var divPrevAmt;
if (type == 0)
{
divPrevAmt = document.getElementById("divBwayGiftPrevAmt");
}
else if (type == 1)
{
divPrevAmt = document.getElementById("divBwayEDUGiftPrevPmt");
}
var txtAmt = document.getElementById(obj);
var amt = txtAmt.value;
amt = amt.toString().replace("$","");
amt = amt.replace(",","");
var prevAmt = divPrevAmt.innerHTML;
try
{
amt = amt * 1;
}
catch(err)
{
txtAmt.value = "";
return;
}
if (amt >= 0) //get the previous amount if any
{
if (type == 0)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
else if (type == 1)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
//now update the master total
var total = document.getElementById("txtTotal");
var dTotal = total.value.toString().replace("$","");
dTotal = dTotal.replace(",","");
dTotal = dTotal * 1;
var newTotal = dTotal - prevAmt;
newTotal = newTotal + amt;
divPrevAmt.innerHTML = amt.toString();
newTotal = addCommas(newTotal);
amt = addCommas(amt);
txtAmt.value = "$" + amt;
total.value = "$" + newTotal;
}
else
{
txtAmt.value = "";
return;
}
}
function disable()
{
var txtTotal = document.getElementById("txtTotal");
var txt = txtTotal.value;
txtTotal.value = txt;
var BwayGift = document.getElementById("txtBwayGift");
BwayGift.focus();
}
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var newTotal = x1 + x2;
if (newTotal.toString().indexOf(".") != -1)
{
newTotal = newTotal.substring(0,newTotal.indexOf(".") + 3);
}
return newTotal;
}
function checkChanged()
{
var cb = document.getElementById("cbOperaGala");
if (cb.checked == true)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "url('images/otTableRowSelect.jpg')";
}
else if (cb.checked == false)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "";
}
}
function alertIf()
{
var i = 0;
for (i=5;i<=10;i++)
{
try{
var subtotal2 = document.getElementById("txtSubTotal" + i);
var dSubtotal2 = subtotal2.value;
dSubtotal2 = dSubtotal2.replace("$","");
dSubtotal2 = dSubtotal2 * 1;}
catch (Error){dSubtotal2 = 0}
if (dSubtotal2 > 0)
{
alert("You have selected the I want it all package, \n however you have also selected individual tickets to the same events. \n If you meant to do this, please disregard this message.");
break;
}
}
}
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
//Add $5.00 donation to cart
function checkboxAdd(ctl) {
if (ctl.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal( 5, "S");
}
}
</script>
I do not understand the context of the scenario. When a user clicks the checkbox are you making an HTTP request to the server? Or is this a simple form POST page? What is calculateTotal() doing?
I figured it out. So the functionality I had in place was fine.
//Add $5.00 donation to cart
function checkboxAdd(txtBwayEDUGift) {
if (txtBwayEDUGift.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal(5, "S");
}
}
But I needed to add a load function:
function load() {
calculateTotal(5, "A");
}
<body onload="load()">
Along with adding a reference to my c# page:
if (txtBwayEDUGift.Checked)
{
addDonations(5.00, 93);
}
You can use jQuery :)
$(txtBwayEDUGift).change(calculateTotal(5, "S"));

Categories