applying 10% discount in calculation - javascript

At the moment im trying to apply a 10% discount on "apppreis" and "backendpreis" when "jährlich" is selected .Im doing that with the if function problem is i would have to write too many if functions since there is so many options to choose from.Is there any easier way to do this instead of using if.
js:
const btncalc = document.querySelector('.calcit');
const summetext = document.querySelector('.summe');
const backend = document.querySelector('.backenduser');
const update = document.querySelectorAll('.update');
const backendstk = document.querySelector('.backendanzahl')
const appstk = document.querySelector('.appanzahl')
const preisproapp = document.querySelector('.proapp')
const preisprobackend = document.querySelector('.probackend')
const jährlich = document.querySelector('.rabatt')
update.forEach(input => {
input.addEventListener('input', function () {
calcSum();
})
});
//funktion damit der Slider sich beim eingeben vom input field bewegt
function updateAppUser(val, inputtype) {
if (inputtype == 'appslider') {
document.getElementById('AppInput').value = val;
}
if (inputtype == 'appinput') {
document.getElementById('appuserSlider').value = val;
}
calcSum();
}
function updateBackendUser(val, inputtype) {
if (inputtype == 'backendslider') {
document.getElementById('BackendInput').value = val;
}
if (inputtype == 'backendinput') {
document.getElementById('backendSlider').value = val;
}
calcSum();
}
//Rechnung für die Anzahl von Backend und App-Benutzern
function calcSum() {
var backendanzahl = document.getElementsByClassName("backenduser")[0].value;
var appanzahl = document.getElementsByClassName("appuser")[0].value;
var annual = document.getElementById("annual");
var backendtype = annual.options[annual.selectedIndex].value;
//Preisstaffelung für app und backend
apppreis = 7.5;
if(backendtype == "J" ){
if (appanzahl < 11) {
apppreis = 7.5;
} else if (appanzahl < 26) {
apppreis = 7;
} else if (appanzahl < 51) {
apppreis = 6.50;
} else if (appanzahl < 76) {
apppreis = 6;
} else if (appanzahl > 76) {
apppreis = 5.5;
}
}
var mylist = document.getElementById("myList");
var backendtype = mylist.options[mylist.selectedIndex].value;
backendpreis = 35;
if (backendtype == "ZR") {
if (backendanzahl < 5) {
backendpreis = 35;
} else if (backendanzahl < 11) {
backendpreis = 32.50;
} else if (backendanzahl < 21) {
backendpreis = 30;
}
} else {
if (backendanzahl < 6) {
backendpreis = 20;
} else if (backendanzahl < 11) {
backendpreis = 18;
} else if (backendanzahl < 21) {
backendpreis = 16;
}
var annual = document.getElementById("annual");
var backendtype = annual.options[annual.selectedIndex].value;
backendpreis = 35;
if (backendtype == "M") {
if (backendanzahl < 5) {
backendpreis = 35 * 1.1;
} else if (backendanzahl < 11) {
backendpreis = 32.50 * 1.1;
} else if (backendanzahl < 21) {
backendpreis = 30 * 1.1;
}
} else {
if (backendanzahl < 6) {
backendpreis = 20 * 1.1;
} else if (backendanzahl < 11) {
backendpreis = 18 * 1.1;
} else if (backendanzahl < 21) {
backendpreis = 16 * 1.1;
}
}
if(backendtype == "M" ){
if (appanzahl < 11) {
apppreis = (7.5 * 1.1);
} else if (appanzahl < 26) {
apppreis = (7* 1.1);
} else if (appanzahl < 51) {
apppreis = (6.50* 1.1);
} else if (appanzahl < 76) {
apppreis = (6* 1.1);
} else if (appanzahl > 76) {
apppreis = 5.5* 1.1;
}
}
}
if (isNaN(proapp2)) proapp2 = 0.00;
var mytext = ((backendanzahl * backendpreis + +appanzahl * apppreis) * 1).toFixed(2);
summetext.textContent = mytext;
var backendpreissumme = (backendanzahl * backendpreis).toFixed(2);
backendstk.textContent = backendpreissumme;
var apppreissumme = (appanzahl * apppreis).toFixed(2);
appstk.textContent = apppreissumme;
var probackend2 = ((backendpreis * backendanzahl) / (backendanzahl)).toFixed(2);
preisprobackend.textContent = probackend2;
var proapp2 = appanzahl > 0 ? ((apppreis * appanzahl) / (appanzahl)).toFixed(2) : "0.00";
preisproapp.textContent = proapp2;
var jährlicherrabatt = ((backendanzahl * backendpreis + +appanzahl * apppreis) * 0.9).toFixed(2);
jährlich.textContent = jährlicherrabatt;
}
html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="grid-container" >
<div style="width: 250px"class="grid-item">
<header>Preiskalkulator</header>
<div class="slidecontainer">
App-Benutzer: <br>
<input id="appuserSlider" value="0" onchange="updateAppUser(this.value);" type="range" min="0" max="100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value); updateAppUser(this.value, 'appslider');" class='appuser update'></input>
<input style="width: 30px" type="text" id="AppInput" value="0" placeholder="1-100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value); updateAppUser(this.value, 'appinput');"><br>
Backendbenutzer: <br>
<input id="backendSlider" value="1" onchange="updateBackendUser(this.value);" type="range" min="1" max="15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value); updateBackendUser(this.value, 'backendslider'); " class='backenduser update'></input>
<input style="width: 30px" type="text" id="BackendInput" value="1" placeholder="1-15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value,); updateBackendUser(this.value, 'backendinput');"><br>
</div>
<b> Bürosoftware wählen </b>
<select style="width: 150px" id = "myList" onchange = "calcSum()" >
<option value="Z">Zeiterfassung</option>
<option value="ZR"> Zeiterfassung + Rechnungswesen</option>
</select>
<select style="width: 150px" id = "annual" onchange = "calcSum()" >
<option value="J">Jährlich</option>
<option value="M">monatlich</option>
</select>
</div>
<div class="grid-item" style="width: 250px">
<table style="width:100%;text-align: right;">
<tr>
<td style="width: 138px" >App-Benutzer<br> pro <span class="proapp" style="color:grey">7,50</span>€</td>
<td style="width: 62px" class='appanzahl'>75,00€</td>
</tr>
<tr>
<td>Backend-Benutzer<br >pro <span class='probackend'>35,00</span>€</td>
<td class='backendanzahl'>175,00€</td>
</tr>
<tr><td colspan="2"><hr></td></tr>
<tr>
<td >Gesamtpreis mtl.:<br>(zzgl. MwSt)</td>
<td class='summe'>75,00€</td>
</tr>
<tr>
<td >Jährlich<br></td>
<td class='rabatt'></td>
</tr>
</table>
</div>
<script src="./app.js"></script>
</body>
</html>

Just create an applyDiscount function and use it when needed.
This is one example.
Given a price and a discount percentage, you will get the discounted price.
function applyDiscount(price, discountPercent) {
return price - (price / discountPercent);
}
const price = 100;
const discount = 10; // 10%
// Example of 10% discount from price 100
console.log(applyDiscount(price, discount));
// Output: 90

To get rid of all the ifs, technically, you can use a Switch Statement, like this:
switch (true) {
case val < 15:
...
break;
case val < 56:
...
break;
//etc...
case default: //used if the switch doesn't meet any of the other requirements
...
}
But tests have found is method is marginally slower that just using ifs.
So, to conclude:
If performance matters use ifs.
If readability matters, use switch.

Related

my HTML page refreshes after one, two or three iterations. What is wrong?

I am writing a blade stress routine all input fields should be numeric.
The Claculate button will calclate then sometimes refresh (you can see the table fill out coming from the script) the refresh takes out the table answers and all the filled in values.
When it doesn't refresh I can then print the page or change values and hit calculate again. This is the intention of the HTML App.
Is there spmething that I don't know about browsers?
I have tried on Opera with debug on finish the whole Calc1() funtion then keep tracing goes to Opera code so hit F8 and it will sometimes work sometimes refresh the page. I have tried Chrome Firefox is not working propely on the computer will have to reload it.
Thank you for any feedback that can solve this problem.
Here is my code:
<!-- turn on quirks mode for IE -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MixPro® BladeStress 3000 & 4000</title>
<style>
label {
display: inline-block;
width: 170px;
}
span {
line-height: 1.0;
}
</style>
</head>
<body>
<section>
<div id="header" style="position: fixed; top: 0; left: 0; width: 100%; height: 10px;">
<div style="margin-top:5px; margin-left:5px; margin-right:5px;">
<div style="width:25%; float:left; text-align:left;"><img src="/tracker/static/mixpro.jpg" alt="MixPro Logo"></div>
<div style="width:50%; float: left; text-align:center; font-family: TeXGyreChorus; font-size: 35px;">
<!-- <div><img src="/tracker/static/vortex.jpg" alt="Squirrel" style="float: left; height:110px;"></div>-->
<div><bold><br>MixPro<sup>®</sup> BladeStress 3000 & 4000</bold></div>
</div>
<div style="width:25%; float: left; text-align:right;"><img src="/tracker/static/mixpro.jpg" alt="MixPro Logo"></div>
</div>
</div>
</section>
<div style="border-style: double; margin-top:150px; margin-left:50px; margin-right:50px; line-height: 1.7;" id='maindiv'>
<form autocomplete="off" style="padding-left: 50px;">
<label for="mpower">Motor Power:</label>
<input type="text" id="mpower"><br>
<label for="slurrySG">Slurry Specific Gravity:</label>
<input type="text" id="slurrySG"><br>
<label for="HSF">Hydraulic Service Factor:</label>
<input type="text" id="HSF"><br>
<label for="TF">Turbine Factor:</label>
<input type="text" id="TF"><br>
<label for="shdia">Shaft Diameter:</label>
<input type="text" id="shdia"><br>
<label for="hubdia">Hub Diameter:</label>
<input type="text" id="hubdia"><br>
<label for="ImpellerType">Impeller Type:</label>
<select id="ImpellerType">
<option value="3300">3300</option>
<option value="3400">3400</option>
<option value="4445">4445</option>
<option value="4490">4490</option>
</select><br>
<label for="pdia">Impeller Diameter:</label>
<input type="text" id="pdia"><br>
<label for="n">Output Speed:</label>
<input type="text" id="n"><br>
<label for="ConnectionType">Connection Type:</label>
<select id="ConnectionType" onchange="ConnectionType1()">
<option value="Bolted">Bolted</option>
<option value="Welded">Welded</option>
</select><br>
<label id="learth" for="earth">Ear Thickness:</label>
<input type="text" id="earth"><br id="bearth">
<label for="bladeth">Blade Thickness:</label>
<input type="text" id="bladeth"><br>
Gusset:
<label style="margin-left:117px;" class="radio-inline">
<input type="radio" onchange="handleClick1();" name="radio1">Yes
</label>
<label class="radio-inline">
<input style="margin-left:-95px;" type="radio" onchange="handleClick2();" name="radio1">No
</label>
<br>
<label style="display: none;" id="lgussth" for="gussth">Gusset Thickness:</label>
<input style="display: none;" type="text" id="gussth" name="gussth"><br style="display: none;" id="bgussth">
<label style="display: none;" id="lnguss" for="nguss">Number of Gussets:</label>
<input style="display: none;" type="text" id="nguss" name="nguss"><br style="display: none;" id="bnguss">
<button style="margin-left:170px; width:80px;" id="Calc" value="Calc" onclick="Calc1()">Calculate</button>
<button style="width:80px;"id="Print" value="Print" onclick="window.print()">Print</button>
<br>
<table style="line-height: 1.2; width:65%;">
<tr>
<th id="stresstitle" style="text-align:left"></th>
</tr>
<tr>
<td id="earstress1"></td>
<td id="earstress2" style="text-align:right"></td>
</tr>
<tr>
<td id="bladestress1"></td>
<td id="bladestress2" style="text-align:right"></td>
</tr>
<tr>
<td id="powerdraw1"></td>
<td id="powerdraw2" style="text-align:right"></td>
</tr>
<tr>
<th id="taper" style="text-align:left"></th>
</tr>
</table>
</form>
</div>
<script language='javascript'>
var gusset = false;
var bolted = true;
var inputvalid = true;
function handleClick1() {
document.getElementById("lgussth").style.display = "inline-block";
document.getElementById("gussth").style.display = "inline";
document.getElementById("bgussth").style.display = "inline";
document.getElementById("lnguss").style.display = "inline-block";
document.getElementById("nguss").style.display = "inline";
document.getElementById("bnguss").style.display = "inline";
gusset = true;
}
function handleClick2() {
document.getElementById("lnguss").style.display = "none";
document.getElementById("nguss").style.display = "none";
document.getElementById("bnguss").style.display = "none";
document.getElementById("lgussth").style.display = "none";
document.getElementById("gussth").style.display = "none";
document.getElementById("bgussth").style.display = "none";
document.getElementById("gussth").value = null;
document.getElementById("nguss").value = null;
gusset = false;
}
function ConnectionType1() {
var x = document.getElementById("ConnectionType").value;
if (x == "Bolted") {
document.getElementById("learth").style.display = "inline-block";
document.getElementById("earth").style.display = "inline";
document.getElementById("bearth").style.display = "inline";
bolted = true;
} else {
document.getElementById("learth").style.display = "none";
document.getElementById("earth").style.display = "none";
document.getElementById("bearth").style.display = "none";
bolted = false;
}
}
function Calc1() {
if (isNaN(document.getElementById("mpower").value)) {
alert("Motor Power Must be a number");
inputvalid = false;
} else {
if (document.getElementById("mpower").value == 0) {
alert("Motor Power Must not be blank");
inputvalid = false;
}
}
if (isNaN(document.getElementById("slurrySG").value)) {
alert("Slurry Specific Gravity Must be a number");
inputvalid = false;
} else {
if (document.getElementById("slurrySG").value == 0) {
alert("Slurry Specific Gravity Must not be blank");
inputvalid = false;
}
}
if (isNaN(document.getElementById("HSF").value)) {
alert("Hydraulic Service Factor Must be a number");
inputvalid = false;
} else {
if (document.getElementById("HSF").value == 0) {
alert("Hydraulic Service Factor Must not be blank");
inputvalid = false;
}
}
if (isNaN(document.getElementById("TF").value)) {
alert("Turbine Factor Must be a number");
} else {
if (document.getElementById("TF").value == 0) {
alert("Turbine Factor Must not be blank");
}
}
if (isNaN(document.getElementById("shdia").value)) {
alert("Shaft Diameter Must be a number");
inputvalid = false;
} else {
if (document.getElementById("shdia").value == 0) {
alert("Shaft Diameter Must not be blank");
inputvalid = false;
}
}
if (isNaN(document.getElementById("hubdia").value)) {
alert("Hub Diameter Must be a number");
inputvalid = false;
} else {
if (document.getElementById("hubdia").value == 0) {
alert("Hub Diameter Must not be blank");
inputvalid = false;
}
}
if (isNaN(document.getElementById("pdia").value)) {
alert("Impeller Diameter Must be a number");
inputvalid = false;
} else {
if (document.getElementById("pdia").value == 0) {
alert("Impeller Diameter Must not be blank");
inputvalid = false;
}
}
if (isNaN(document.getElementById("n").value)) {
alert("Output Speed Must be a number");
inputvalid = false;
} else {
if (document.getElementById("n").value == 0) {
alert("Output Speed Must not be blank");
inputvalid = false;
}
}
if (document.getElementById("ConnectionType").value == "Bolted") {
if (isNaN(document.getElementById("earth").value)) {
alert("Ear Thickness Must be a number");
inputvalid = false;
} else {
if (document.getElementById("earth").value == 0) {
alert("Ear Thickness Must not be blank");
inputvalid = false;
}
}
} else {
document.getElementById("earth").value = "";
}
if (isNaN(document.getElementById("bladeth").value)) {
alert("Blade Thickness Must be a number");
inputvalid = false;
} else {
if (document.getElementById("bladeth").value == 0) {
alert("Blade Thickness Must not be blank");
inputvalid = false;
}
}
if (gusset) {
if (isNaN(document.getElementById("gussth").value)) {
alert("Gusset Thickness Must be a number");
inputvalid = false;
} else {
if (document.getElementById("gussth").value == 0) {
alert("Gusset Thickness Must not be blank");
inputvalid = false;
}
};
if (isNaN(document.getElementById("nguss").value)) {
alert("Number of Gussets Must be a number");
inputvalid = false;
} else {
if (document.getElementById("nguss").value == 0) {
alert("Number of Gussets Must not be blank");
inputvalid = false;
}
}
} else {
document.getElementById("gussth").value = "";
document.getElementById("nguss").value = "";
};
if (inputvalid) {
var hp = Number(document.getElementById("mpower").value);
var sg = Number(document.getElementById("slurrySG").value);
var hsf = Number(document.getElementById("HSF").value);
var tf = Number(document.getElementById("TF").value);
var shdia = Number(document.getElementById("shdia").value);
var hubdia = Number(document.getElementById("hubdia").value);
var imptype = document.getElementById("ImpellerType").value;
var pdia = Number(document.getElementById("pdia").value);
var n = Number(document.getElementById("n").value);
var contype = document.getElementById("ConnectionType").value;
var earth = Number(document.getElementById("earth").value);
var bladeth = Number(document.getElementById("bladeth").value);
var nguss = Number(document.getElementById("nguss").value);
var gussth = Number(document.getElementById("gussth").value);
var pguss = "";
var earlen = 0;
switch(imptype) {
case "3300":
var bladeang = 45;
var nblades = 3;
var npo = 0.3;
var c = 0.6;
var bladefac = 0.16;
if (bolted) {
if (pdia >= 90) {
var earwdth = Math.round(2 * pdia / 11 + .49) / 2;
} else {
var earwdth = Math.round(2 * pdia / 12 + .49) / 2;
}
hubear = hubdia * .85 / Math.sin(bladeang * Math.PI / 180);
if (hubear < earwdth) {
earwdth2 = hubear;
} else {
earwdth2 = earwdth;
}
}
break;
case "3400":
var bladeang = 45;
var nblades = 4;
var npo = 0.37;
var c = 0.7;
var bladefac = 0.16;
if (bolted) {
if (pdia >= 90) {
var earwdth = Math.round(2 * pdia / 11 + .49) / 2;
} else {
var earwdth = Math.round(2 * pdia / 12 + .49) / 2;
}
hubear = hubdia * .85 / Math.sin(bladeang * Math.PI / 180);
if (hubear < earwdth) {
earwdth2 = hubear;
} else {
earwdth2 = earwdth;
}
}
break;
case "4445":
var bladeang = 45;
var nblades = 4;
var npo = 1.27;
var c = 1.2107;
var bladefac = 0.19;
if (bolted) {
var earwdth = Math.round(2 * pdia * 0.095 + .49) / 2;
hubear = hubdia * .85 / Math.sin(bladeang * Math.PI / 180);
if (hubear < earwdth) {
earwdth2 = hubear;
} else {
earwdth2 = earwdth;
}
}
break;
case "4490":
var bladeang = 90;
var nblades = 4;
var npo = 3.64;
var c = 1.97;
var bladefac = 0.19;
if (bolted) {
var earwdth = Math.round(2 * pdia * 0.095 + .49) / 2;
hubear = hubdia * .85 / Math.sin(bladeang * Math.PI / 180);
if (hubear < earwdth) {
earwdth2 = hubear;
} else {
earwdth2 = earwdth;
}
}
break;
}
var bladewdth = bladefac * pdia;
if (bolted) {
earlen = earwdth + earth + .125;
}
var Fa = 0.97 * sg * c * Math.pow((n / 60), 2) * Math.pow((pdia / 12), 4) / nblades;
var Ft = 0.7705 * sg * npo * tf * Math.pow((n / 60), 2) * Math.pow((pdia / 12), 4) / nblades;
var Fra = Fa * Math.cos(bladeang * Math.PI / 180) + Ft * Math.sin(bladeang * Math.PI / 180);
var Fr = (0.8 + 0.2 * hsf) * Fra;
var Mblade = Fr * (0.4 * pdia - 0.5 * hubdia - earlen);
if (bolted) {
var Mear = Fr * (0.4 * pdia - 0.5 * hubdia);
var bladestress = 6 * Mblade / (bladewdth * Math.pow(bladeth, 2));
if (gusset) {
var gussht = Math.round(4 * pdia / 32 + .49) / 4;
var NAxis = (((earth / 2) * earwdth * earth) + ((earth + (gussht / 2)) * gussht * gussth * nguss)) / (earth * earwdth + gussht * gussth * nguss);
var MInert = (((1 / 12) * earwdth * Math.pow(earth, 3)) + (earwdth * earth * Math.pow((NAxis - (earth / 2)), 2))) + ((1 / 12) * nguss * gussth * Math.pow(gussht, 3)) + (nguss * gussth * gussht * Math.pow((NAxis - (earth + (gussht / 2))), 2));
var earstress = Mear * (earth + gussht - NAxis) / MInert;
pguss = "with Gusset(s)";
} else {
var NAxis = earth/2;
var MInert = ((1 / 12) * earwdth * Math.pow(earth, 3));
var earstress = Mear * (earth - NAxis) / MInert;
}
} else {
var NAxis = bladeth/2;
var hubear = hubdia * .85 / Math.sin(bladeang * Math.PI / 180);
if (hubear < bladewdth) {
var earwdth2 = hubear;
} else {
var earwdth2 = bladewdth;
}
var MInert = ((1 / 12) * earwdth2 * (bladeth ^ 3));
var bladestress = 6 * Mblade / (earwdth2 * Math.pow(bladeth, 2));
}
var PD = (npo * sg * tf * Math.pow((n / 60), 3) * Math.pow((pdia * 25.4 / 1000), 5)) / 0.746;
document.getElementById("stresstitle").innerHTML = contype + " Blade MP-"+imptype+ " Impeller "+pguss;
if (bolted) {
document.getElementById("earstress1").innerHTML = "\u03C3, Ear-root (psi)";
document.getElementById("earstress2").innerHTML = earstress.toFixed(2);
}
document.getElementById("bladestress1").innerHTML = "\u03C3, Blade at ear tip (psi)";
document.getElementById("bladestress2").innerHTML = bladestress.toFixed(2);
document.getElementById("powerdraw1").innerHTML = " Impeller Power Draw (hp)";
document.getElementById("powerdraw2").innerHTML = PD.toFixed(2);
if (bolted) {
if (earwdth > earwdth2) {
document.getElementById("taper").innerHTML = "Note: Ear Width tapered at hub weld from "+earwdth+" to "+earwdth2;
}
} else {
if (bladewdth > earwdth2) {
document.getElementById("taper").innerHTML = "Note: Blader Width tapered at hub weld from "+bladewdth+" to "+earwdth2;
}
}
};
}
</script>
</body>
</html>
You're using <form> tag which when a button is clicked causes the brower to refresh. If you are running this as a local file, that is file://mytest.html instead of having it delivered by a server then change the <form> tag to something like a <div>.

the for loop on the select options is not working

I am trying to make a loop on select options but it is not working.
The code is working on the first element only but not working on others.
In other options they give the same result as the first one.
What can I do to make the loop work on the options? I want to edit the for loop not the whole code.
var billAmount = document.getElementById('bill-amount'),
serviceQuality = document.getElementById('quality'),
serviceQualityList = Array.from(document.querySelectorAll('#quality option')),
serviceQualityListLength = serviceQualityList.length,
pepoleServing = document.getElementById('pepole'),
calculate = document.getElementById('calculate'),
tips = document.getElementById('tips');
calculate.onclick = function() {
var serviceQualityListText = serviceQualityList.text,
serviceQualityListLength = serviceQualityList.length,
billAmountValue = billAmount.value,
pepoleServingValue = pepoleServing.value;
for (var i = 0; i < serviceQualityListLength; i++) {
if (serviceQualityListText = "Exellent") {
tips.textContent = (billAmountValue / 40) * pepoleServingValue;
} else if (serviceQualityListText = "Very Good") {
tips.textContent = (billAmountValue / 60) * pepoleServingValue;
} else if (serviceQualityListText = "Good") {
tips.textContent = (billAmountValue / 70) * pepoleServingValue;
} else if (serviceQualityListText = "Not Good") {
tips.textContent = (billAmountValue / 75) * pepoleServingValue;
} else {
tips.textContent = (billAmountValue * 0) * pepoleServingValue;
}
}
};
<div class="tip-calculator">
<div class="claculator-header">
<h2 class="claculator-title">Calculate Your Tip</h2>
</div>
<div class="bill-amount-container">
<span class="pound-sign">£</span>
<input id="bill-amount" type="text" placeholder="How Much is your bill?">
</div>
<div class="service-quality">
<span>Choose The Quality Of The Service</span>
<select id="quality">
<option class="quality-selector">Exellent</option>
<option class="quality-selector">Very Good</option>
<option class="quality-selector">Good</option>
<option class="quality-selector">Not Good</option>
<option class="quality-selector">Bad</option>
</select>
</div>
<div class="number-of-pepole">
<span class="number">Number Of Serving Peplole</span>
<input type="text" id="pepole" placeholder="How Many Pepole Serving You?">
</div>
<div class="do">
<button id="calculate">calculate</button>
</div>
<div class="result">
<span>Your Tips Equal</span>
<div id="tips">..........</div>
<span>£</span>
</div>
</div>
Your if statements are assigning values instead of checking them, use == or === istead of =.
Try:
for (var i = 0; i < serviceQualityListLength; i++) {
if (serviceQualityListText == "Exellent") {
tips.textContent = (billAmountValue / 40) * pepoleServingValue;
} else if (serviceQualityListText == "Very Good") {
tips.textContent = (billAmountValue / 60) * pepoleServingValue;
} else if (serviceQualityListText == "Good") {
tips.textContent = (billAmountValue / 70) * pepoleServingValue;
} else if (serviceQualityListText == "Not Good") {
tips.textContent = (billAmountValue / 75) * pepoleServingValue;
} else {
tips.textContent = (billAmountValue * 0) * pepoleServingValue;
}
}

how to get different winning% in decreasing order for number of winners?

var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
var set = document.getElementById('winnerCount').value;
if (set.length > sum.length) {
document.getElementById('err_winnerCount').remove();
} else {
document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
document.getElementById("demo").innerHTML = "Rank &nbsp &nbsp Winning% &nbsp &nbsp &nbsp &nbsp &nbsp Winning Amount";
var x = document.getElementById("w_amount").value;
var w = document.getElementById("c_size").value;
var y = document.getElementById("winnerCount").value;
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
for (z = 1; z <= parseInt(y); z++) {
document.getElementById("demo1").innerHTML += +z + "&nbsp<input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/>&nbsp<input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert('errr');
$('#err_winnerCount').innerHTML = "Please enter less than contest size";
}
}
var sharePerc = 0;
function getValues(arg) {
var id = arg.getAttribute('id');
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var curPerc = document.getElementById(id).value;
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - curPerc) / (x2.length - 1);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" onblur="validate()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="2"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"></input><span class="err" id="err_winnerCount"></span></li>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</div>
// firstly when giving winning amount and contest size we get the entry fee and after check in customize winning it will enable the set number of winners and set button.In set number of winners the input should be less than the contest size but while entering the greater than contest size it will not showing error message and after clicking set button we get a list of winners in this the winning % should be decreasing order while changing the default winning % of first text box but in my code while changing the second text box it changes the first text box also. if possible please know me how to solve this.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
$('#err_winnerCount').html("");
var set = document.getElementById('winnerCount').value;
var contestSize = document.getElementById('c_size').value;
if (set > contestSize) {
$('#err_winnerCount').html("");
} else {
//document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
var x = document.getElementById("w_amount").value;
var w = parseInt(document.getElementById("c_size").value);
var y = parseInt(document.getElementById("winnerCount").value);
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
//document.getElementById("demo").innerHTML = "Rank &nbsp &nbsp Winning% &nbsp &nbsp &nbsp &nbsp &nbsp Winning Amount";
var demoTableBody = document.getElementById("demo_table").tBodies[0];
demoTableBody.innerHTML = "";
//console.log(demoTableBody.innerHTML);
for (z = 1; z <= parseInt(y); z++) {
//console.log(demoTableBody.children.length);
var rowIndex = demoTableBody.children.length + 1;
var newRow = "<td>"+rowIndex+"</td>";
newRow += "<td><input type='text' class='tot' id='perc" + rowIndex + "' value='' onkeyup='getValues(this)'/><span class = 'perc_error_spn' id='perc_error" + rowIndex + "'></span></td>";
newRow += "<td><input type='text' class='pop' id='val" + rowIndex + "' value='Rs." + a + "'/></td>";
demoTableBody.innerHTML += newRow;
//document.getElementById("demo1").innerHTML += +z + "&nbsp<input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/>&nbsp<input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert("errr");
$('#err_winnerCount').html("Please enter less than contest size");
}
}
var sharePerc = 0;
function getValues(arg) {
// clear all error messages.
var errorSpans = document.getElementsByClassName("perc_error_spn");
for(var i = 0; i < errorSpans.length; i++){
errorSpans[i].innerHTML = "";
}
var id = arg.getAttribute('id');
var row_index = arg.parentNode.parentNode.rowIndex;
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var tmp = 0;
var previousWinnersPercentage = [];
var nextWinnersPercentage = [];
for(var i = 1; i < row_index; i++){
tmp += parseFloat(document.getElementById("perc" + i).value);
previousWinnersPercentage[previousWinnersPercentage.length] = tmp;
}
for(var i = row_index + 1 ; i <= x2.length; i++){
nextWinnersPercentage[nextWinnersPercentage.length] = parseFloat(document.getElementById("perc" + i).value);
}
//winAmt -= tmp;
var curPerc = document.getElementById(id).value;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var isInvalidInput = isBiggerThanPreviousPercentage(previousWinnersPercentage,curPerc);
if(!isInvalidInput){
isInvalidInput = isLesserThanPreviousPercentage(nextWinnersPercentage,curPerc);
}
if((sharePerc <= 0 && x2.length > 1) || isInvalidInput){
var errorSpan = id.replace("perc", "perc_error");
document.getElementById(errorSpan).innerHTML = "Invalid input";
return;
}
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = row_index; i <= x2.length; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
function reorderPercentage(){
var demoTableBody = document.getElementById("demo_table").tBodies[0];
for(var i = 0; i < demoTableBody.children.length; i++){
var percentageInput = demoTableBody.children[i].querySelector(".tot");
//console.log(percentageInput.value);
var row = percentageInput.parentNode.parentNode,
sibling = row.nextElementSibling,
parent = row.parentNode;
var siblingPercentageValue = "";
//console.log(sibling);
if(sibling != null){
siblingPercentageValue = sibling.querySelector(".tot").value;
}
if(percentageInput.value < siblingPercentageValue){
parent.insertBefore(sibling,row);
}
}
}
function isBiggerThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value > e){
return true;
}
});
return result;
}
function isLesserThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value < e){
return true;
}
});
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="3"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"/><span class="err" id="err_winnerCount"></span>
<input type="button" value="Reorder" onclick="reorderPercentage();"/>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<table id="demo_table">
<thead>
<tr>
<th>Rank</th>
<th>Winning %</th>
<th>Winning Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
table, th, td {
border: 1px solid black;
}
</style>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">10 Winners</button>
<div class="dropdown-content">
<table style="width:100%">
<tr>
<th>Rank</th>
<th>Prize</th>
</tr>
<tr>
<td>1</td>
<td>1000</td>
</tr>
<tr>
<td>2-5</td>
<td>500</td>
</tr>
<tr>
<td>6-10</td>
<td>100</td>
</tr>
</table>
</div>
</div>
</body>
If you input number of winners greater than contest size it will prompt an alert box. Check and let me know that is it working or not?
Due to below code both the text boxes are modified simultaneously.
If you can explain the below code, why you are using this
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}

Javascript: Currency converter

Im new in javascript and I'm trying to make a simple currency converter, it is working fine when I select "£Pound" "£Pound" or "£Pound" "R$Real" but when I select "R$Real" "R$Real" runs the "Pound" "R$Real" calculation.
I spent hours trying to figure this out (very frustrating).
How to fix it? Is there another way to do it? (also tried using " if " and " else if " same issue). Thanks!
Here`s the HTML:
<label>Amount:</label>
<input type="text" id="amount" />
<label>From:</label>
<select id="select1">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<label>To:</label>
<select id="select2">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<input type="button" onClick="calculation()" value="calculate" />
<div id="result"></div>
Here`s the JS:
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch((currency1)&&(currency2)){
case "pound":
case "pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound":
case "real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}}
To fix your JS do the following:
The issue is that your switch would compute to a single string, and you are using fall-through switch statements, jsFiddle to demonstrate what I mean.
Switch Statement Documentation for JavaScript
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch (currency1 + ' ' + currency2) {
case "pound pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}
}
Use the below to display the number and then just put the symbol in front, as this code will add commas and separators in the right spots, including negative.
Format number to currency:
function formatCurrency(num, precision) {
//identify '(123)' as a negative number
if (typeof num == 'string' && num.toString().indexOf('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && precision === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
if (num === '' || (num === '-' && precision === -1)) {
return;
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (precision >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(precision); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
if ((hasDecimals && precision == -1) || precision > 0) {
num += '.' + decimals;
}
// format symbol/negative
var format = isPositive ? '%s%n' : '(%s%n)';
var money = format.replace(/%s/g, '$');
money = money.replace(/%n/g, num);
return money;
}
console.log(formatCurrency(12002031203120, 2))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<style>
body{
background:linear-gradient(3150deg,#7458ff,#a48afc);
background-size: cover;
height: 800px;
display: flex;
align-items: center;
justify-content:center;
}
.col-md-8{
background-color: rgb(183, 170, 170);
padding: 10px 24px;
border-radius: 20px;
width: 490px;
}
.form-group{
width: 100%;
display: flex;
}
input{
width:95%;
color:aliceblue;
height: 40px;
font-size: 1em;
margin: 0.2em 0;
border-radius: 10px;
border: none;
background: #676666;
outline: none;
padding: 0.1em;
}
select{
width: 50%;
height:40px;
font-size: 30px;
cursor: pointer;
background: #039cfb;
outline: none;
color: black;
padding: 0 1em;
border-radius: 10px;
border: none;
}
</style>
</head>
<body>
<div class="col-md-6 well">
<h3 class="text-primary">Javascript - Simple Currency Converter</h3>
<hr style="border-top:1px dotted #ccc;">
<div class="col-md-8">
<h4>Converter</h4>
<hr style="border-top:1px groovy #ccc;"/>
<div class="form-group">
<select onchange="Currency(); Calculate()" class="form-control" id="converter" style="width:30%;">
<option value="Dollar">Dollar</option>
<option value="Pound">Pound</option>
<option value="Euro">Euro</option>
<option value="Yen">Yen</option>
<option value="Yuan">Yuan</option>
</select>
<br />
<input type="number" oninput="Calculate()" class="form-control" id="value1"/>
</div>
<br /><br />
<div class="form-group">
<label>Pak Rupee:</label>
<input type="number" class="form-control" id="value2" disabled="disabled"/>
</div>
</div>
</div>
<script>
function Currency(){
y = document.getElementById("converter").value;
return y;
}
function Calculate(){
y = Currency();
x = document.getElementById("value1").value;
if(x == ""){
document.getElementById("value2").value = "";
}else{
switch(y){
case "Dollar":
document.getElementById("value2").value = x * 215.99;
break;
case "Pound":
document.getElementById("value2").value = x * 72.39;
break;
case "Euro":
document.getElementById("value2").value = x * 63.84;
break;
case "Yen":
document.getElementById("value2").value = x * 0.49;
break;
case "Yuan":
document.getElementById("value2").value = x * 8.20;
break;
}
}
}
</script>
</body>
</html>

Why doesn't my script work with checkboxes?

I am trying to make a little "game" and for some reason, if I try and get the checked of a checkbox, my script will flip out... sometimes it works, sometimes it just stops executing. Is there some sort of an error I missed?
<html>
<head>
<title>Untitled Document</title>
<script>
var check = "showcheck";
var number = 1234;
var lvl = 1;
var oldlvl = 1;
var multiplier = 10000;
var start = 1;
function exefunction() {
document.getElementById("boxv").focus();
if (check == "showcheck") {
document.getElementById("message").innerHTML = "What was the number?";
document.getElementById("num").style.display = "none";
document.getElementById("box").style.display = "inline";
document.getElementById("boxv").focus();
check = "checknum";
}
else if (check == "checknum") {
if (document.getElementById("boxv").value == number) {
document.getElementById("message").innerHTML = "CORRECT!";
document.getElementById("boxv").style.color = "#00DD00";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
lvl++;
}
else if (document.getElementById("boxv").value != number) {
document.getElementById("message").innerHTML = "INCORRECT!";
document.getElementById("boxv").style.color = "#DD0000";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
if (lvl>1) {lvl--;}
loselife();
}
check = "showmem";
}
else if (check == "showmem") {
if (lvl == oldlvl + 10) {
oldlvl = lvl;
multiplier = multiplier * 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
else if (lvl < oldlvl) {
oldlvl = lvl - 10;
multiplier = multiplier / 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
number = Math.floor(Math.random() * multiplier / 10 * 9) + multiplier / 10;
document.getElementById("boxv").style.color = "#000000";
document.getElementById("boxv").value = "";
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").innerHTML = number;
document.getElementById("num").style.display = "inline";
document.getElementById("box").style.display = "none";
check = "showcheck";
}
}
function loselife(){
var life = 4;
var hearts = "♥ ";
alert(document.getElementById("lifebox").checked);
}
function submitenter() {
var keycode = window.event.keyCode;
if (keycode == 13) {
if (start === 0) {exefunction();}
else {startfunc();}
}
if (keycode < 47 || keycode > 58) {
return false;
}
}
function startfunc() {
document.getElementById("button").innerHTML = '<input name="" type="button" value="OK" onClick="exefunction()"/>';
document.getElementById("level").innerHTML = "Level: " + lvl;
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").style.display = "inline";
document.getElementById("boxv").value = "";
document.getElementById("box").style.display = "none";
if (document.getElementById("lifecheck").checked === true) {
document.getElementById("life").innerHTML = "♥ ♥ ♥ ♥ ♥ ";
}
else if (document.getElementById("lifecheck").checked === false) {
document.getElementById("life").innerHTML = "";
}
if (document.getElementById("timercheck").checked === true) {
document.getElementById("timer").innerHTML = "3:00";
}
else if (document.getElementById("timercheck").checked === false) {
document.getElementById("timer").innerHTML = "";
}
start = 0;
}
function tests() {
alert(lfckv);
}
</script>
<style type="text/css">
#level, #life, #timer{
color: #666;
}
* {
text-align: center;
}
#num {
display: none;
}
#num {
font-size: x-large;
}
#body {
margin-top: 250px;
margin-right: auto;
margin-bottom: 100px;
margin-left: auto;
}
body {
background-color: #6FF;
}
</style></head>
<body onKeyPress="return submitenter()" >
<div id="body">
<span id="level"></span>
<table align="center">
<tr>
<td width="200" height="50" align="center" valign="middle"><span id="message">What level would you like to begin at?</span></td>
<td width="200" height="50" align="center" valign="middle"><span id="num">1234</span><span id="box"><input type="text" id="boxv" maxlength="4" value="1"/></span></td>
</tr>
</table>
<table align="center">
<tr>
<td width="200" id="life"><label><input id="lifecheck" type="checkbox" >Lives</label></td>
<td id="button"><input type="button" value="OK" onClick="startfunc()"/></td>
<td width="200" id="timer"><label><input id="timercheck" type="checkbox" >Timer</label></td>
</tr>
</table>
<input name="" type="button" onClick="tests()" value="tests()">
</div>
</body>
</html>
lifebox isnt defined in the loselife() function. Plus, also check the test() function, that alert() statement has a variable that isnt defined.
If you are using Google chrome (or any other browser that can help you debug), I would suggest you to debug through your lines of code.
I think you're better off using simple equality for checking the state of your checkboxes, because I'm pretty the outcome is not a Boolean.
So it would be something like that :
if (document.getElementById("lifecheck").checked == true) {
or simply
if (document.getElementById("lifecheck").checked) {
instead of
if (document.getElementById("lifecheck").checked === true) {
Ahah! I figured out the problem. Apparently, when I set the visibility of the checkbox to none, it also set the checkvalue to null for some reason. I had expected it to keep the checkvalue, but for some reason it does not.

Categories