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>
Related
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.
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>.
I am attempting to create a function function examineNumbers(). This function is supposed to prompt the user for numbers on the click of a button. The code is supposed to determine the type of the number as even, odd and float. Then add up all the sums numTotal and floatTotal and the averages numAverage and floatAverage. I actually have two issues. The while loop is not supposed to incorporate the SENTINEL into the code. It adds it in anytime -1 is inputted by the user. It is just supposed to break the while loop.
Second issue is my code fails to add the total correctly. It shows the original value of 0 and displays all other numbers inputted next to the number 0 instead of adding into one sum. This occurs for numTotal and floatTotal. Can anyone help me determine where the issue is on these two items please?
function examineNumbers() {
const SENTINEL = -1;
let number = 0;
let type;
let numValues = 0;
let numAverage = 0;
let floatValues = 0;
let numTotal = 0;
let floatTotal = 0;
let list = document.getElementById("list");
let numbers = document.getElementById("numbers");
let floating = document.getElementById("floating");
// while loop to only allow numbers greater than zero to be inputted
while (number != SENTINEL) {
number = prompt("Enter a number. Type " + SENTINEL + " to stop.");
// deterrmines if a number is even
if (number % 2 == 0) {
type = " is an even value";
numTotal += number;
numValues++;
}
// determines if a number is odd
else if (Math.abs(number % 2) == 1) {
type = " is an odd value";
numTotal += number;
numValues++;
}
// gives a floating point type if above two aren't met
else {
type = " is a floating point value.";
floatTotal += number;
numTotal += number;
numValues++;
floatValues++;
}
let numResults;
let floatResults;
// averages non floating numbers
numAverage = numTotal / numValues;
numResults = document.getElementById("numbers").innerHTML = " The total is " + numTotal +
" and the average is " + numAverage + ".";
// gives value if no non floating numbers are entered
if (numValues == 0 && floatValues == 0) {
numResults = document.getElementById("numbers").innerHTML = " No values were entered."
}
// averages floating point numbers
floatAverage = floatTotal / floatValues;
floatResults = document.getElementById("floating").innerHTML = " The total is " + floatTotal +
" and the average is " + floatAverage + ".";
// gives value if no floating numbers are entered
if (floatValues == 0) {
floatResults = document.getElementById("floating").innerHTML = "No floating-pont values were entered."
}
let li = "";
//only add number and its status to list when number not equal to SENTINEL
if (number !== SENTINEL) {
li = document.createElement("li");
li.innerHTML = number + type;
list.appendChild(li);
// displays information for both non floating numbers and floating numbers
numbers.innerHTML = numResults;
floating.innerHTML = floatResults;
}
}
}
<h1> Number Examination Tool </h1>
<form name="myForm">
<button type="button" onclick="examineNumbers();">Click here to enter numbers </button>
<h3>List of Numbers </h3>
<ul id="list"></ul>
<div id="numbers"></div>
<div id="floating"></div>
</form>
You have to use parseInt and ParseFloat functions in the function to get this working correctly. Also, you have to pass another if condition inside the while loop to prevent the "-1" from adding to the total. Hope the below code helps
function examineNumbers() {
const SENTINEL = -1;
let number = 0;
let type;
let numValues = 0;
let numAverage = 0;
let floatValues = 0;
let numTotal = 0;
let floatTotal = 0;
let list = document.getElementById("list");
let numbers = document.getElementById("numbers");
let floating = document.getElementById("floating");
// while loop to only allow numbers greater than zero to be inputted
while (number != SENTINEL) {
number = prompt("Enter a number. Type " + SENTINEL + " to stop.");
if (number == -1) {
break;
}
// deterrmines if a number is even
if (number % 2 == 0) {
type = " is an even value";
numTotal += parseInt(number);
numValues++;
}
// determines if a number is odd
else if (Math.abs(number % 2) == 1) {
type = " is an odd value";
numTotal += parseInt(number);
numValues++;
}
// gives a floating point type if above two aren't met
else {
type = " is a floating point value.";
floatTotal += parseFloat(number);
numTotal += parseFloat(number);
numValues++;
floatValues++;
}
let numResults;
let floatResults;
// averages non floating numbers
numAverage = numTotal / numValues;
numResults = document.getElementById("numbers").innerHTML = " The total is " + numTotal.toFixed(2) +
" and the average is " + numAverage + ".";
// gives value if no non floating numbers are entered
if (numValues == 0 && floatValues == 0) {
numResults = document.getElementById("numbers").innerHTML = " No values were entered."
}
// averages floating point numbers
floatAverage = floatTotal / floatValues;
floatResults = document.getElementById("floating").innerHTML = " The total is " + floatTotal.toFixed(2) +
" and the average is " + floatAverage + ".";
// gives value if no floating numbers are entered
if (floatValues == 0) {
floatResults = document.getElementById("floating").innerHTML = "No floating-pont values were entered."
}
let li = "";
//only add number and its status to list when number not equal to SENTINEL
if (number !== SENTINEL) {
li = document.createElement("li");
li.innerHTML = number + type;
list.appendChild(li);
// displays information for both non floating numbers and floating numbers
numbers.innerHTML = numResults;
floating.innerHTML = floatResults;
}
}
}
<h1> Number Examination Tool </h1>
<form name="myForm">
<button type="button" onclick="examineNumbers();">Click here to enter numbers </button>
<h3>List of Numbers </h3>
<ul id="list"></ul>
<div id="numbers"></div>
<div id="floating"></div>
</form>
Maybe you can learn something from the code below:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
hC = function(node, className){
return node.classList.contains(className);
}
aC = function(){
const a = [...arguments];
a.shift().classList.add(...a);
return aC;
}
rC = function(){
const a = [...arguments];
a.shift().classList.remove(...a);
return rC;
}
tC = function(){
const a = [...arguments];
a.shift().classList.toggle(...a);
return tC;
}
// magic under here - you can put code below on another page using a load event - except the `}); // end load`
const nums = I('nums'), calc = I('calc'), res = I('res'), evens_sum = I('evens_sum');
const evens_avg = I('evens_avg'), odds_sum = I('odds_sum'), odds_avg = I('odds_avg');
const int_sum = I('int_sum'), int_avg = I('int_avg'), dec_sum = I('dec_sum');
const dec_avg = I('dec_avg'), sum = I('sum'), avg = I('avg'), error = I('error');
function testNums(){
for(let n of arguments){
if(n === '' || isNaN(n)){
return false;
}
}
return true;
}
const calcNums = (()=>{
const eve = [], odd = [], dec = [];
let c, d, n;
return ()=>{
if(hC(error, 'hid')){
c = d = 0; nums.value = nums.value.trim()
eve.splice(0); odd.splice(0); dec.splice(0);
const a = nums.value.split(/\s*,\s*/g);
for(let s of a){
n = +s;
if(n % 1 !== 0){
c = s.replace(/^.*\./, '').length; dec.push(n);
if(c > d)d = c;
}
else if(n % 2 === 0){
eve.push(n);
}
else{
odd.push(n);
}
}
let eL = eve.length, oL = odd.length, iL = eL+oL, dL = dec.length, tL = iL+dL;
const eT = eve.reduce((a, v)=>a+v, 0), oT = odd.reduce((a, v)=>a+v, 0);
const dT = dec.reduce((a, v)=>a+v, 0), iT = eT+oT, tT = iT+dT;
evens_sum.textContent = eT; odds_sum.textContent = oT; int_sum.textContent = iT;
dec_sum.textContent = dT.toFixed(d); sum.textContent = tT.toFixed(d);
evens_avg.textContent = eL === 0 ? 0 : (eT/eL).toFixed(d);
odds_avg.textContent = oL === 0 ? 0 : (oT/oL).toFixed(d);
int_avg.textContent = iL === 0 ? 0 : (iT/iL).toFixed(d);
dec_avg.textContent = dL === 0 ? 0 : (dT/dL).toFixed(d);
avg.textContent = tL === 0 ? 0 : (tT/tL).toFixed(d);
rC(res, 'hid');
}
}
})();
nums.oninput = function(){
let v = this.value.trim();
aC(res, 'hid');
if(v.length && testNums(...v.split(/\s*,\s*/g))){
f = aC;
}
else{
f = rC;
}
f(this, 'yes'); f(error, 'hid');
}
calc.onclick = calcNums;
nums.onkeyup = e=>{
if(e.key === 'Enter')calc.click();
}
}); // end load
/* css/external.css */
*{
padding:0; margin:0; font-size:0; border:0; box-sizing:border-box; outline:none;
overflow:hidden; -webkit-tap-highlight-color:transparent;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#aaa;
}
.bar{
position:relative; width:100vw; height:39px; background:#ccc; color:#000;
padding:3px 3px 3px 7px; border-bottom:1px solid #333;
}
h1{
font:bold 27px Tahoma, Geneva, sans-serif;
}
.guts{
width:100%; height:calc(100% - 39px); padding:5px 10px; overflow-y:auto;
}
.guts>*,.guts>#res *{
font:bold 22px Tahoma, Geneva, sans-serif;
}
.guts>#res>div>span{
color:#147;
}
label{
color:#fff; text-shadow:-1px 0 #000,0 1px #000,1px 0 #000,0 -1px #000; margin-top:
}
label:first-child{
margin-top:0;
}
input,textarea,select{
width:100%; height:38px; background:#fff; color:#000; text-shadow:none;
border:1px solid #c00;
}
input,textarea{
border-radius:3px; padding:5px;
}
input[type=button]{
width:100%; height:auto; background:linear-gradient(#1b7bbb,#147); color:#fff;
font:bold 28px Tahoma, Geneva, sans-serif; padding:5px 10px; border:1px solid #007;
border-radius:5px; margin-top:7px; cursor:pointer;
}
.yes{
border-color:#0c0;
}
#error{
color:#900; font-size:18px; text-align:center;
}
.hid{
display:none;
}
.bottom{
width:100%; height:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div class='bar'><h1>Number Fun</h1></div>
<div class='guts'>
<label for='nums'>Enter Comma Separated Numbers</label><input id='nums' type='text' value='' />
<input id='calc' type='button' value='CALCULATE' />
<div class='hid' id='res'>
<div>evens sum: <span id='evens_sum'></span></div>
<div>evens average: <span id='evens_avg'></span></div>
<div>odds sum: <span id='odds_sum'></span></div>
<div>odds average: <span id='odds_avg'></span></div>
<div>integer sum: <span id='int_sum'></span></div>
<div>integer average: <span id='int_avg'></span></div>
<div>decimal sum: <span id='dec_sum'></span></div>
<div>decimals average: <span id='dec_avg'></span></div>
<div>sum: <span id='sum'></span></div>
<div>average: <span id='avg'></span></div>
</div>
<div id='error'>Comma Separated Numbers Only</div>
<div class='bottom'></div>
</div>
</div>
</body>
</html>
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     Winning%           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 + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <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     Winning%           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 + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <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);
}
}
I have a field that reads your lawn takes a ___ hour shower. It is calculated by the square footage input. When the value of this field equals 8,11,or 18. I would like it to read "an ____ hour shower." How would this be made possible?
http://jsfiddle.net/on6c360o/
var a = document.getElementById("a");
var b = document.getElementById("b");
var astored = a.getAttribute("data-in");
var g = document.getElementById("g");
setInterval(function() {
if (a == document.activeElement) {
var temp = a.value;
if (astored != temp) {
astored = temp;
a.setAttribute("data-in", temp);
calculate();
}
}
}, 10);
function calculate() {
b.innerHTML = a.value * .62;
g.innerHTML = Math.round(a.value * .0103);
}
<div class="mobile" style="text-align:center">
<h2>Lawn Square Footage</h2>
<input id="a" onkeypress="return isNumberKey(event)" style="height: 250px; margin-top: 10px; width: 75%; text-align: center; font-size: 100px;" type="text" data-in="" />
<h2>Water Usage</h2>
<h2 id="b">___</h2>
<h2>Gallons per day</h2>
<h2>Your lawn takes <span id="g">___</span> hour showers</h2>
</div>
You can use a ternary operator to say if hours is 8, 11, or 18 then display an else display a.
var hours = Math.round(a.value * .0103);
g.innerHTML = (hours === 8 || hours === 11 || hours === 18 ? 'an' : 'a') + ' ' + hours;
Here's an example http://jsfiddle.net/bmec3tad/
You could perform an if check when changing the HTML contents like so:
function calculate() {
b.innerHTML = a.value * .62;
var gVal = Math.round(a.value * .0103);
g.innerHTML = gVal + ([8, 11, 18].indexOf(gVal) == -1 ? "a" : "an");
}