Null error on Javascript Project. (Null==0?!) - javascript

There is 2 option here: Score and Wrong.
I want this :
If answer.value is empty > wrong+1
If not, score+1.
But its not working.
There is a question here ; 4*0 (answer is 0 right?)
I dont write anything on my answer input. So, > answer.value == null
But, result is score+1. This is not i want.
I guess, answer.value == 0 right here. How can i do what i want?
if (result == answer.value) {
score.innerHTML = Number(score.innerHTML) + 1;
} else if (result != answer.value || answer.value == null) {
wrong.innerHTML = Number(wrong.innerHTML) + 1;
}
Complete JavaScript codes and html codes
//idleri alma
var sayi1, sayi2, islem, cevap, btn, dogru, yanlis;
sayi1 = document.getElementById("sayi1");
sayi2 = document.getElementById("sayi2");
islem = document.getElementById("islem");
cevap = document.getElementById("cevap");
btn = document.getElementById("btn");
dogru = document.getElementById("true");
yanlis = document.getElementById("false");
//random sayı oluşturma
function rSayi(ust, alt) {
return Math.floor(Math.random() * (ust - alt)) + alt;
}
function soru() {
sayi1.innerHTML = rSayi(5, 0);
sayi2.innerHTML = rSayi(5, 0);
//islem değişkeni üzerinde değişiklikler
var islemler = ["+", "-", "/", "*"];
islem.innerHTML = islemler[rSayi(4, 0)];
//bölme geldiğinde tam bölünebilme özelliği
if (islem.innerHTML == "/") {
while (true) {
if (sayi1.innerHTML % sayi2.innerHTML == 0) {
break;
}
sayi2.innerHTML = rSayi(50, 0);
}
}
//islem kontrolü
var sonuc, s1, s2;
s1 = Number(sayi1.innerHTML) // sayıları
s2 = Number(sayi2.innerHTML) // number veri türüne geçiş yaptırıyoruz
switch (islem.innerHTML) {
case "+":
sonuc = s1 + s2;
break;
case "-":
sonuc = s1 - s2;
break;
case "*":
sonuc = s1 * s2;
break;
case "/":
sonuc = s1 / s2;
break;
default:
break;
}
//dogru yanlis puanlarını arttırmak
//HERE IS THE PROBLEM!!
btn.onclick = function() {
soru();
var p1, p2;
p1 = Number(dogru.innerHTML);
p2 = Number(yanlis.innerHTML);
if (sonuc == cevap.value) {
dogru.innerHTML = p1 + 1;
//dogru.innerHTML = Number(dogru.innerHTML)+1; !diğer yöntem
} else if (sonuc != cevap.value || cevap.value == null) {
yanlis.innerHTML = p2 + 1;
//yanlis.innerHTML = Number(yanlis.innerHTML)+1; !diğer yöntem
}
}
}
//events
window.onload = function() {
soru();
}
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id="main">
<div id="sayi1">0</div>
<div id="islem">+</div>
<div id="sayi2">0</div>
<div id="equal">=</div>
<div id="_cevap"><input id="cevap"></div>
<div id="_btn"><button id="btn">Cevapla</button></div>
<div id="clear"></div>
<div id="true">0</div>
<div id="false">0</div>
</div>
</body>
</html>

The problem with your code is Number('') is 0 and not null
Hence when the <input > does not have value, the answer is considered to be 0, which is correct for 4 * 0
Also, use === wherever possible to prevent automatic type conversion like this.
What you could do is short-circuit the logic,
if(cevap.value === '') // empty is always wrong
yanlis.innerHTML = p2 + 1;
else {
... continue your code here
}
updated Code
//idleri alma
var sayi1, sayi2, islem, cevap, btn, dogru, yanlis;
sayi1 = document.getElementById("sayi1");
sayi2 = document.getElementById("sayi2");
islem = document.getElementById("islem");
cevap = document.getElementById("cevap");
btn = document.getElementById("btn");
dogru = document.getElementById("true");
yanlis = document.getElementById("false");
//random sayı oluşturma
function rSayi(ust, alt) {
return Math.floor(Math.random() * (ust - alt)) + alt;
}
function soru() {
sayi1.innerHTML = rSayi(5, 0);
sayi2.innerHTML = rSayi(5, 0);
//islem değişkeni üzerinde değişiklikler
var islemler = ["+", "-", "/", "*"];
islem.innerHTML = islemler[rSayi(4, 0)];
//bölme geldiğinde tam bölünebilme özelliği
if (islem.innerHTML == "/") {
while (true) {
if (sayi1.innerHTML % sayi2.innerHTML == 0) {
break;
}
sayi2.innerHTML = rSayi(50, 0);
}
}
//islem kontrolü
var sonuc, s1, s2;
s1 = Number(sayi1.innerHTML) // sayıları
s2 = Number(sayi2.innerHTML) // number veri türüne geçiş yaptırıyoruz
switch (islem.innerHTML) {
case "+":
sonuc = s1 + s2;
break;
case "-":
sonuc = s1 - s2;
break;
case "*":
sonuc = s1 * s2;
break;
case "/":
sonuc = s1 / s2;
break;
default:
break;
}
//dogru yanlis puanlarını arttırmak
//HERE IS THE PROBLEM!!
btn.onclick = function() {
soru();
var p1, p2;
p1 = Number(dogru.innerHTML);
p2 = Number(yanlis.innerHTML);
if(cevap.value === '') {
yanlis.innerHTML = p2 + 1;
} else if (sonuc == cevap.value) {
dogru.innerHTML = p1 + 1;
//dogru.innerHTML = Number(dogru.innerHTML)+1; !diğer yöntem
} else if (sonuc != cevap.value) {
yanlis.innerHTML = p2 + 1;
//yanlis.innerHTML = Number(yanlis.innerHTML)+1; !diğer yöntem
}
}
}
//events
window.onload = function() {
soru();
}
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id="main">
<div id="sayi1">0</div>
<div id="islem">+</div>
<div id="sayi2">0</div>
<div id="equal">=</div>
<div id="_cevap"><input id="cevap"></div>
<div id="_btn"><button id="btn">Cevapla</button></div>
<div id="clear"></div>
<div id="true">0</div>
<div id="false">0</div>
</div>
</body>
</html>

Related

i dont know ho to do this freecodecamp javascript calculator

help !! the console tells me x13. If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign. The sequence"5-5"=should produce an output of"-25"expected'-5'to equal¹-25'
AssertionError:The sequence"5-5"=should produce an output of"-25"expected'-5'to equal
I try to use regex because someone tells me I should do that but I don't know how. I do 15 right but one is wrong and I can't pass this test :(
https://codepen.io/mikaelamattos/pen/RwQGeXe
let trailingResult = 0;
let operationOptions = ['divide', 'multiply', 'subtract', 'add'];
let workingOperation = "";
function updateDisplay(input) {
let display = document.getElementById("display");
let secondaryDisplay = document.getElementById("secondaryDisplay");
if (display.innerHTML === "0" && operationOptions.indexOf(input) === -1) {
if (input === "decimal") {
display.innerHTML = "0.";
} else if (input === "negative-value") {
if (display.innerHTML.indexOf("-1") === -1) {
display.innerHTML = "-" + display.innerHTML
} else if (display.innerHTML.indexOf("-1" > -1)) {
display.innerHTML = display.innerHTML.slice(1, display.innerHTML.length);
}
} else {
display.innerHTML = input;
}
} else if (operationOptions.indexOf(input) >= 0) {
if (trailingResult === display.innerHTML) {
workingOperation = input;
} else if (workingOperation === "") {
workingOperation = input;
trailingResult = display.innerHTML;
secondaryDisplay.innerHTML = trailingResult;
display.innerHTML = 0;
} else {
// Dealing with a set operand
// console.log(display.innerHTML, " Dealing with set operand");
trailingResult = calculate(trailingResult, display.innerHTML, workingOperation);
secondaryDisplay.innerHTML = trailingResult;
display.innerHTML = 0;
workingOperation = input;
}
} else if (input === "equals") {
display.innerHTML = calculate(trailingResult, display.innerHTML, workingOperation);
trailingResult = 0;
workingOperation = "";
secondaryDisplay.innerHTML = trailingResult;
} else if (input === "decimal") {
// console.log('decimal clicked');
if (display.innerHTML.indexOf(".") === -1) {
display.innerHTML += ".";
}
// console.log("decimal skipped because decimal already in number.");
} else if (input === "negative-value") {
// console.log("negative-value selected");
if (display.innerHTML.indexOf("-1") === -1) {
display.innerHTML = "-" + display.innerHTML
} else if (display.innerHTML.indexOf("-1" > -1)) {
display.innerHTML = display.innerHTML.slice(1, display.innerHTML.length);
}
} else {
display.innerHTML += input;
}
}
function clearDisplay() {
let display = document.getElementById("display");
let secondaryDisplay = document.getElementById("secondaryDisplay");
trailingResult = 0;
display.innerHTML = 0;
secondaryDisplay.innerHTML = trailingResult;
}
function calculate(firstNumber, secondNumber, operation) {
let result;
firstNumber = parseFloat(firstNumber);
secondNumber = parseFloat(secondNumber);
switch(operation) {
case "add":
result = firstNumber + secondNumber;
break;
case "subtract":
result = firstNumber - secondNumber;
break;
case "multiply":
result = firstNumber * secondNumber;
break;
case "divide":
result = firstNumber / secondNumber;
break;
default:
console.log("Calculate switch statement missed something");
}
return result.toString();
}

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.

How do I use objects in 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>

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