How to make Feedback disappear with user action in Javascript? - javascript

What do I need to add to the code, so that when the user clicks the button New or starts typing in the inputfield "userAnswer" for a second try, the Feedback disappears.
But the feedback should always appear when user clicks check
This is the simplified version of the code:
function F1() {
Z1 = document.getElementById("Z1");
Z2 = document.getElementById("Z2");
rZ1 = Math.floor((Math.random() * 10));
rZ2 = Math.floor((Math.random() * 10));
Z1.innerHTML = rZ1;
Z2.innerHTML = rZ2;
var operators1 = ['+', '-'];
oper1 = document.getElementById("operator1");
op1 = operators1[Math.floor(Math.random() * 2)];
oper1.innerHTML = op1;
rnd = parseFloat(eval(rZ1 + op1 + rZ2));
answer.innerHTML = rnd;
}
function F2() {
antw = parseFloat(document.getElementById("userAnswer").value);
feedBack = document.getElementById("feedBack");
ant = document.getElementById("answer").textContent;
{
if (antw == ant) {
feedBack.textContent = "good";
} else {
feedBack.textContent = "bad";
}
}
};
<button onclick="F1()"> New </button>
<label id="Z1"> </label>
<label id="operator1"> </label>
<label id="Z2"> </label>
= <input id="userAnswer" type=text>
<button onclick="F2()">check</button>
<p id="feedBack"> </p>
<p> <label id="answer"></label> </p>

I added a function at the end of the code to disappear with feedBack and a line was added in F1 and F2 to display and disappear with feedBack (I added a comment on those lines)
function F1() {
Z1 = document.getElementById("Z1");
Z2 = document.getElementById("Z2");
rZ1 = Math.floor((Math.random() * 10));
rZ2 = Math.floor((Math.random() * 10));
Z1.innerHTML = rZ1;
Z2.innerHTML = rZ2;
var operators1 = ['+', '-'];
oper1 = document.getElementById("operator1");
op1 = operators1[Math.floor(Math.random() * 2)];
oper1.innerHTML = op1;
rnd = parseFloat(eval(rZ1 + op1 + rZ2));
answer.innerHTML = rnd;
document.querySelector('p#feedBack').style.display = 'none' // add this
document.querySelector('#userAnswer').value = ''
}
function F2() {
antw = parseFloat(document.getElementById("userAnswer").value);
feedBack = document.getElementById("feedBack");
ant = document.getElementById("answer").textContent;
{
if (antw == ant) {
feedBack.textContent = "good";
} else {
feedBack.textContent = "bad";
}
}
document.querySelector('p#feedBack').style.display = 'block' // add this
};
document.querySelector('#userAnswer').addEventListener('keydown', event => {
if(document.querySelector('p#feedBack').style.display == 'block')
document.querySelector('p#feedBack').style.display = 'none'
})
<button onclick="F1()"> New </button>
<label id="Z1"> </label>
<label id="operator1"> </label>
<label id="Z2"> </label>
= <input id="userAnswer" type="text" >
<button onclick="F2()">check</button>
<p id="feedBack"></p>
<p> <label id="answer"></label> </p>

Add to the F1-function
document.getElementById('feedBack').classList.add('hidden');
and to the CSS a new entry for the hidden class to hide the element if exists.
For displaying the feedback if check is pressed remove similar in F2 this class.
document.getElementById('feedBack').classList.remove('hidden');
function F1() {
Z1 = document.getElementById("Z1");
Z2 = document.getElementById("Z2");
rZ1 = Math.floor((Math.random() * 10));
rZ2 = Math.floor((Math.random() * 10));
Z1.innerHTML = rZ1;
Z2.innerHTML = rZ2;
var operators1 = ['+', '-'];
oper1 = document.getElementById("operator1");
op1 = operators1[Math.floor(Math.random() * 2)];
oper1.innerHTML = op1;
rnd = parseFloat(eval(rZ1 + op1 + rZ2));
answer.innerHTML = rnd;
document.getElementById('feedBack').classList.add('hidden');
}
function F2() {
antw = parseFloat(document.getElementById("userAnswer").value);
feedBack = document.getElementById("feedBack");
ant = document.getElementById("answer").textContent;
{
if (antw == ant) {
feedBack.textContent = "good";
} else {
feedBack.textContent = "bad";
}
}
document.getElementById('feedBack').classList.remove('hidden');
};
.hidden { visibility: hidden; }
<button onclick="F1()"> New </button>
<label id="Z1"> </label>
<label id="operator1"> </label>
<label id="Z2"> </label>
= <input id="userAnswer" type=text>
<button onclick="F2()">check</button>
<p id="feedBack"> </p>
<p> <label id="answer"></label> </p>

Related

How to use this true/false flag to make switching radio buttons disable other radio buttons effects

Ive tried following this:
var changed = function() {
if (document.getElementById('wolf').checked) {
wolfActive = true;
turtleActive = false;
lizardActive = false;
} else if (document.getElementById('lizard').checked) {
lizardActive = true;
wolfActive = false;
turtleActive = false;
} else if (document.getElementById('turtle').checked) {
turtleActive = true;
lizardActive = false;
wolfActive = false;
}
}
But i can't get each radiobuttons effect to be false when a different radio button is selected ( having a hard time understanding how it works)
This is my JavaScript:
var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtleregen = 0.5;
var Lizard = 1;
var Lizardlv = 1;
var LizardCexp = 0;
var LizardMexp = 100;
var NextMaxLizardExp = LizardMexp;
var Wolf = 1;
var Wolflv = 1;
var WolfCexp = 0;
var WolfMexp = 100;
var NextMaxWolfExp = WolfMexp;
var Strength = 2;
var Magic = 1;
var Wolfstrength = 1
var ManaPoints = 10
function Wolfandstrength() {
if (document.getElementById("wolf-radio").checked) {
Strength = Strength + Wolfstrength
document.getElementById("Strength").innerHTML = Strength;
} else {
Strength = Strength - Wolfstrength
document.getElementById("Strength").innerHTML = Strength;
}
}
function wolfXpUp() {
if (document.getElementById("wolf-radio").checked && WolfCexp < WolfMexp)
{
setTimeout(wolfXpUp, 100)
WolfCexp = WolfCexp + 1;
document.getElementById("WolfCexp").innerHTML = WolfCexp;
}
if (WolfCexp >= WolfMexp) {
Wolflv = Wolflv + 1;
WolfCexp = 0;
Wolf = Wolf + 1;
Wolfstrength = Wolfstrength + 1;
Strength = Strength + 1;
NextMaxWolfExp= NextMaxWolfExp *1.5;
}
document.getElementById("Strength").innerHTML = Strength;
document.getElementById('WolfMexp').innerHTML = NextMaxWolfExp;
document.getElementById('Wolflv').innerHTML = Wolflv;
document.getElementById('WolfCexp').innerHTML = WolfCexp;
document.getElementById('Wolf').innerHTML = Wolf;
}
function lizardXpUp() {
if (document.getElementById("lizard-radio").checked && LizardCexp <
LizardMexp) {
setTimeout(lizardXpUp, 200)
LizardCexp = LizardCexp + 1;
document.getElementById("LizardCexp").innerHTML = LizardCexp;
}
if (LizardCexp >= LizardMexp) {
Lizardlv = Lizardlv + 1;
LizardCexp = 0;
Lizard = Lizard + 1;
Lizardmagic = Lizardmagic + 1;
Magic = Magic + 1;
NextMaxLizardExp= NextMaxLizardExp *1.5;
}
document.getElementById("Magic").innerHTML = Magic;
document.getElementById('LizardMexp').innerHTML =
NextMaxLizardExp;
document.getElementById('Lizardlv').innerHTML = Lizardlv;
document.getElementById('LizardCexp').innerHTML = LizardCexp;
document.getElementById('Lizard').innerHTML = Lizard;
}
function turtleXpUp() {
if (document.getElementById("turtle-radio").checked && Turtleexp <
TurtleMexp) {
setTimeout(turtleXpUp, 200)
TurtleCexp = TurtleCexp + 1;
document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
}
if (TurtleCexp >= TurtleMexp) {
Turtlelv = Turtlelv + 1;
TurtleCexp = 0;
Turtle = Turtle + 1;
Tmanapoints = Tmanapoints + 1;
ManaPoints = ManaPoints + 1;
NextMaxLizardExp= NextMaxLizardExp *1.5;
}
document.getElementById("ManaPoints").innerHTML = ManaPoints;
document.getElementById('TurtleMexp').innerHTML = NextMaxTurtleExp;
document.getElementById('Turtlelv').innerHTML = Turtlelv;
document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
document.getElementById('Turtle').innerHTML = Turtle;
}
document.getElementById("wolf-radio").addEventListener("change", wolfXpUp)
document.getElementById("wolf-radio").addEventListener("change",
Wolfandstrength)
document.getElementById("lizard-radio").addEventListener("change",
lizardXpUp)
document.getElementById("lizard-radio").addEventListener("change",
Wolfandstrength);
document.getElementById("Strength").innerHTML = Strength;
document.getElementById("Magic").innerHTML = Magic;
document.getElementById("ManaPoints").innerHTML = ManaPoints;
HTML code: ( can change if needed its not perfect)
font size="+2"> <b> Pets </b></font>
<div id="turtle" class="control">
<label class="radio">
<input type="radio" name="Pets" id="turtle-radio">
</label><img src="turtle.png" alt="turtle" height="100" width="100"> Lv
<span id="Turtlelv">1</span> <span id="TurtleCexp">0</span> / <span
id="TurtleMexp">100</span>
<br />
<br />
<div id="lizard" class="control">
<label class="radio">
<input type="radio" name="Pets" id="lizard-radio">
</label><img src="lizard.png" alt="lizard" height="42" width="42">
Lv <span
id="Lizardlv">1</span> <span id="LizardCexp">0</span> / <span
id="LizardMexp">100</span>
<br />
<div id="wolf" class="control">
<label class="radio">
<input type="radio" name="Pets" id="wolf-radio">
</label><img src="wolf.png" alt="wolf" height="60" width="60">
Lv <span id="Wolflv">1</span> <span
id="WolfCexp">0</span> / <span id="WolfMexp">100</span></div>
<br />
<span id="Strength">0</span>
<br />
<span id="Magic">0</span>
<br />
<span id="ManaPoints">0</span>
I expect from using that true/false function in my what i've already tried box to help me disable radio buttons functions/ stat buffs while a diffrent radio button is selected. But the actual output when you switch from the turtle radio button to lizard radio button it takes away 1 strength when strength should be untouched unless the wolf radio button is selected.

Changing a a html element with a if/else if statement based on a selected option

I want to change the lable tags and the placeholder of the input for the for the form with an id of "PercentageCalc". I want it to change based off of the selected option for the dropdown menu. I tried different ways of writing the function and tried giving it .addEventListener. Cant seem to figure it out.
let numField1 = document.getElementById('numField1');
let numField2 = document.getElementById('numField2');
let resultField = document.getElementById('resultField');
let form = document.getElementById('PercentageCalc');
let preInputText = document.getElementById('preInputText');
let numField1Text = document.getElementById('numField1Text');
let numField2Text = document.getElementById('numField2Text');
let CalcTypeSelector = document.getElementById('CalcTypeSelector');
CalcTypeSelector.addEventListener('change', function () {
if (CalcTypeSelector.value = 'whatisXPofY') {
preInputText.innerText = "What is";
numField1Text.innerText = "% of";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value = 'XisYPofWhat') {
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "% of what?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value = 'whatPofXisY') {
preInputText.innerText = "What % of";
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
}
});
form.addEventListener('submit', function (e) {
if (!numField1.value || !numField2.value ) {
alert("Please enter number values in the fields")
} else {
let x = parseFloat(numField1.value);
let y = parseFloat(numField2.value);
let result = x / y;
let percent = result * 100;
resultField.innerText = "Result: " + percent + "%";
e.preventDefault();
}
});
<body>
<h1>Percentage Calculators</h1>
<form id="CalcType">
<select id="CalcTypeSelector">
<option>Choose and option</option>
<option value="whatisXPofY">what is X percentage of Y?</option>
<option value="XisYPofWhat">X is Y percentage of what?</option>
<option value="whatPofXisY">what percentage of X is Y?</option>
<option value="XPofWhatisY">X percentage of what is Y?</option>
<option value="YPofXisWhat">Y percentage of X is what?</option>
</select>
</form>
<div>
<p>X is what percent of Y?</p>
<form id="PercentageCalc">
<label id="preInputText">gfg</label>
<input type="text" id="numField1" />
<label id="numField1Text">gfdg</label>
<input type="text" id="numField2" />
<label id="numField2Text">rter</label>
<br />
<br />
<input type="submit" value="Calculate">
</form>
</div>
<h3 id="resultField"></h3>
<script type="text/javascript" src="calc.js"></script>
The problem is in your if statements you should use == || === instead of =
now it works
let numField1 = document.getElementById('numField1');
let numField2 = document.getElementById('numField2');
let resultField = document.getElementById('resultField');
let form = document.getElementById('PercentageCalc');
let preInputText = document.getElementById('preInputText');
let numField1Text = document.getElementById('numField1Text');
let numField2Text = document.getElementById('numField2Text');
let CalcTypeSelector = document.getElementById('CalcTypeSelector');
CalcTypeSelector.addEventListener('change', function () {
console.log(CalcTypeSelector.value);
if (CalcTypeSelector.value == 'whatisXPofY') {
preInputText.innerText = "What is";
numField1Text.innerText = "% of";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value === 'XisYPofWhat') {
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "% of what?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value === 'whatPofXisY') {
preInputText.innerText = "What % of";
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
}
});
form.addEventListener('submit', function (e) {
if (!numField1.value || !numField2.value ) {
alert("Please enter number values in the fields")
} else {
let x = parseFloat(numField1.value);
let y = parseFloat(numField2.value);
let result = x / y;
let percent = result * 100;
resultField.innerText = "Result: " + percent + "%";
e.preventDefault();
}
});
<body>
<h1>Percentage Calculators</h1>
<form id="CalcType">
<select id="CalcTypeSelector">
<option>Choose and option</option>
<option value="whatisXPofY">what is X percentage of Y?</option>
<option value="XisYPofWhat">X is Y percentage of what?</option>
<option value="whatPofXisY">what percentage of X is Y?</option>
<option value="XPofWhatisY">X percentage of what is Y?</option>
<option value="YPofXisWhat">Y percentage of X is what?</option>
</select>
</form>
<div>
<p>X is what percent of Y?</p>
<form id="PercentageCalc">
<label id="preInputText">gfg</label>
<input type="text" id="numField1" />
<label id="numField1Text">gfdg</label>
<input type="text" id="numField2" />
<label id="numField2Text">rter</label>
<br />
<br />
<input type="submit" value="Calculate">
</form>
</div>
<h3 id="resultField"></h3>

Use Javascript to Make Calculator

Good Day - I am Learning Javascript, I am trying to create a Calculator to calculate ampere-turn to magnetize a tool (it's related to my job.) I am trying to use some formulas to calculate this ampere-turn. The code seems fine to me, but it's not working. I put some values in the form, and click button submit, but no result found and i don't know why this happens.
I am sharing my code here for your kind review. and help me to fix this problem.
thank you.
function ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
if(factor <= 0.1)
{
ans = 45000/ldratio*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}
<form name="ampereturn">
<div class="w3-half w3-margin-top">
<label>Tool OD:</label>
<input id="inputod" class="w3-input w3-border" type="number" placeholder="Input Tool Outer Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Tool Lenght:</label>
<input id="inputlen" class="w3-input w3-border" type="number" placeholder="Input Tool Length">
</div>
<div class="w3-half w3-margin-top">
<label>Coil ID:</label>
<input id="Inputid" class="w3-input w3-border" type="number" placeholder="Input Coil Internal Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Coil Turn:</label>
<input id="Inputturn" class="w3-input w3-border" type="number" placeholder="Input Number of turn in coil:">
</div>
<div class="w3-half w3-margin-top">
<label>Required Ampere:</label>
<p id="sum"></p>
</div>
<button type="button" onclick="ampereturn()">Submit</button>
</form>
<br><hr>
thank you in advance. ....
Change the function name which is same as the form name.
Change Inputturn to InputTurn in the if condition.
Required Code:
function Ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else if(factor <=0.1)
{
ans = 45000/ldratio*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}

How to make JavaScript basic shopping cart amount calculator

<script>
var itemquantity, appleamount, appletotalamount, bananaamount, bananatotalamount, gtotalfruits, gtotalfruitss
function apple() {
var itemquantity = document.getElementById("apple");
var appleamount = document.getElementById("appletotal");
var appletotalamount = itemquantity.value * 50;
appleamount.value = appletotalamount;
}
function banana() {
var itemquantity = document.getElementById("banana");
var bananaamount = document.getElementById("bananatotal");
var bananatotalamount = itemquantity.value * 30;
bananaamount.value = bananatotalamount;
}
function grandtotalfruits() {
var gtotalfruits = document.getElementById("grandtotalfruitss");
var gtotalfruitss = appletotalamount + bananatotalamount;
gtotalfruits.value = gtotalfruitss;
}
</script>
<div class="left">
<p class="fruit11">Apples - <input type="number" id="apple" class="shoppinginput" onChange="apple()" onchange="grandtotalfruits"> Rs.50/Kg</p>
<p class="fruit12">Total amount = Rs.<output id="appletotal"></output></p>
</div>
<div class="left">
<p class="fruit11">Bananas - <input type="number" id="banana" class="shoppinginput" onChange="banana()" onchange="grandtotalfruits"> Rs.30/Kg</p>
<p class="fruit12">Total amount = Rs.<output id="bananatotal"></output></p>
</div>
<div class="grandtotal">
<p class="fruit13">Grand total = Rs.<output id="grandtotalfruitss"></output></p>
</div>`
Take first input type="number" value1 * 100 show in output box and then take input type="number" value2 * 100 show in second output box, then add the value1 and value2 and show in output box 3. I am using JavaScript and am a beginner.
Can you see the design while reading the question?
It's working for output1 and output2, but not able create correct method or function for the grand total output of output1 and output2 in the third output box.
Basically, what #dev8989 said. Every time the user changes the "apples" value, you change the "apples quantity" (same for the "bananas"). You also have to update the "grand total" if any of the apples/bananas are updated. That's what #dev8989 suggested:
var $apples = document.getElementById('apples')
var $applesTotal = document.getElementById('apples-total')
var $bananas = document.getElementById('bananas')
var $bananasTotal = document.getElementById('bananas-total')
var $grandTotal = document.getElementById('grand-total')
function apple (v) { return 50 * v }
function banana (v) { return 30 * v}
$apples.addEventListener('change', function() {
$applesTotal.textContent = apple($apples.value)
$grandTotal.textContent = apple($apples.value) + banana($bananas.value)
})
$bananas.addEventListener('change', function() {
$bananasTotal.textContent = banana($bananas.value)
$grandTotal.textContent = apple($apples.value) + banana($bananas.value)
})
<input type="number" id="apples">
<p>Apples total: <span id="apples-total">0</span></p>
<input type="number" id="bananas">
<p>Bananas total: <span id="bananas-total">0</span></p>
<p>Grand total: <span id="grand-total">0</span></p>
Edit: here's the original code with the bugs fixed. See my comment on why this was necessary:
var itemquantity, appleamount, appletotalamount = 0, bananaamount, bananatotalamount = 0, gtotalfruits, gtotalfruitss
function apple() {
var itemquantity = document.getElementById("apple");
var appleamount = document.getElementById("appletotal");
appletotalamount = itemquantity.value * 50;
appleamount.value = appletotalamount;
grandtotalfruits();
}
function banana() {
var itemquantity = document.getElementById("banana");
var bananaamount = document.getElementById("bananatotal");
bananatotalamount = itemquantity.value * 30;
bananaamount.value = bananatotalamount;
grandtotalfruits();
}
function grandtotalfruits() {
var gtotalfruits = document.getElementById("grandtotalfruitss");
var gtotalfruitss = appletotalamount + bananatotalamount;
gtotalfruits.value = gtotalfruitss;
}
<div class="left">
<p class="fruit11">Apples - <input type="number" id="apple" class="shoppinginput" onChange="apple()" onchange="grandtotalfruits"> Rs.50/Kg</p>
<p class="fruit12">Total amount = Rs.<output id="appletotal"></output></p>
</div>
<div class="left">
<p class="fruit11">Bananas - <input type="number" id="banana" class="shoppinginput" onChange="banana()" onchange="grandtotalfruits"> Rs.30/Kg</p>
<p class="fruit12">Total amount = Rs.<output id="bananatotal"></output></p>
</div>
<div class="grandtotal">
<p class="fruit13">Grand total = Rs.<output id="grandtotalfruitss"></output></p>
Add the grandtotalfruit() in the apple() and banana() functions.
function apple() {
var itemquantity = document.getElementById("apple");
var appleamount = document.getElementById("appletotal");
var appletotalamount = itemquantity.value * 50;
appleamount.value = appletotalamount;
grandtotalfruit();
}
function banana() {
var itemquantity = document.getElementById("banana");
var bananaamount = document.getElementById("bananatotal");
var bananatotalamount = itemquantity.value * 30;
bananaamount.value = bananatotalamount;
grandtotalfruit();
}

JavaScript Code Optimization - Creating Reusable Classes

I am new to JavaScript and need help with code optimization. I am pretty sure there are some ways to create "classes" to run my code better and more efficient.
Here is the link to my jsfiddle demo version: JSFiddle Demo
<form id="tyreForm">
<div id="currentTyre">
<h2>Current Tyre Size</h2>
<div id="errorDisplay"></div>
<input type="number" id="sectionWidth"> /
<input type="number" id="aspectRatio"> R
<input type="number" id="rimDiameter">
<p>Sidewall: <span class="output"></span></p>
<p>Width: <span class="output"></span></p>
<p>Diameter: <span class="output" id="fullDiameter"></span></p>
<p>Circumference: <span class="output"></span></p>
<p>Reverse / Mile: <span class="output"></span></p>
</div>
<div id="newTyre">
<h2>New Tyre Size</h2>
<input type="number" id="newSectionWidth"> /
<input type="number" id="newAspectRatio"> R
<input type="number" id="newRimDiameter">
<p>Sidewall: <span class="output"></span></p>
<p>Width: <span class="output"></span></p>
<p>Diameter: <span class="output" id="newFullDiameter"></span></p>
<p>Circumference: <span class="output"></span></p>
<p>Reverse / Mile: <span class="output"></span></p>
</div>
<div id="result">
<h2>Tyre difference</h2>
<p>Diameter Difference(%): <span id="diameterDifference"></span></p>
</div>
<button type="submit">Calculate</button>
</form>
document.getElementById('tyreForm').addEventListener('submit', function(e) {
e.preventDefault();
var sw = this.sectionWidth.value;
var ar = this.sectionWidth.value;
var rd = this.sectionWidth.value;
var nsw = this.newSectionWidth.value;
var nar = this.newAspectRatio.value;
var nrd = this.newRimDiameter.value;
/* Form Validation Starts */
var errorDisplay = document.getElementById('errorDisplay');
errorDisplay.style.display = 'block';
if (sw == '' || ar == '' || rd == '') {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please fill all the fields";
return false;
}
if (sw == 0 || ar == 0 || rd == 0) {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please check your input fields. 0 is not valid";
return false;
}
/* Form Validation Finishes */
this.getElementsByClassName("output")[0].textContent = sidewall(sw, ar).toFixed(2);
this.getElementsByClassName("output")[1].textContent = width(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[2].textContent = diameter(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[3].textContent = circumference(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[4].textContent = reverseMile(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[5].textContent = sidewall(nsw, nar).toFixed(2);
this.getElementsByClassName("output")[6].textContent = width(nsw, nar, nrd).toFixed(2);
this.getElementsByClassName("output")[7].textContent = diameter(nsw, nar, nrd).toFixed(2);
this.getElementsByClassName("output")[8].textContent = circumference(nsw, nar, nrd).toFixed(2);
this.getElementsByClassName("output")[9].textContent = reverseMile(nsw, nar, nrd).toFixed(2);
var fd = document.getElementById('fullDiameter').textContent;
var nfd = document.getElementById('newFullDiameter').textContent;
document.getElementById('diameterDifference').textContent = diameterDifference(fd, nfd);
}, false);
/* All functions */
function sidewall(sw, ar) {
return ((sw * (ar/100)) / 25.4);
}
function width(sw, ar) {
return (sw / 25.4);
}
function diameter(sw, ar, rd) {
return ((sidewall(sw, ar) * 2) + parseFloat(rd));
}
function circumference(sw, ar, rd) {
return (((((sw * (ar/100)) / 25.4) * 2)+ parseInt(rd)) * 3.14);
}
function reverseMile(sw, ar, rd) {
return (63360 / (((((sw * (ar/100)) / 25.4) * 2)+ parseInt(rd)) * 3.14));
}
function diameterDifference(fd, nfd) {
return fd * nfd; // Just dummy formula
}
The main idea is:
Have two forms where people can enter their tire sizes.
If only the first form filled with data - calculation happens only in the first form
If both forms are filled with data - both forms' calculations are proceeded plus some data is passed to third form
Please check jsfiddle for more information.
Thanks in advance!
Best
You should create a Tyre prototype that takes sectionWidth, aspectRatio, and rimDiameter in the "constructor" and more all of your functions into that prototype. Doing this will simplify the logic of your code and will help you adhere to the principles of DRY (don't repeat yourself).
var Tyre = function(sectionWidth, aspectRatio, rimDiameter) {
this.sw = sectionWidth;
this.ar = aspectRatio;
this.rd = rimDiameter;
this.isEmpty = function() {
return this.sw === '' || this.ar === '' || this.rd === '';
};
this.isZero = function() {
return this.sw == 0 || this.ar == 0 || this.rd == 0;
};
this.width = function() {
return this.sw / 25.4;
};
this.sidewall = function() {
return this.width() * this.ar / 100;
};
this.diameter = function() {
return 2 * this.sidewall() + parseFloat(this.rd);
};
this.circumference = function() {
return this.diameter() * Math.PI;
};
this.reverseMile = function() {
return 63360 / this.circumference();
};
this.diameterDifference = function(other) {
return this.diameter() * other.diameter();
};
};
document.getElementById('tyreForm').addEventListener('submit', function(e) {
e.preventDefault();
var currentTyre = new Tyre(this.sectionWidth.value, this.aspectRatio.value, this.rimDiameter.value);
var newTyre = new Tyre(this.newSectionWidth.value, this.newAspectRatio.value, this.newRimDiameter.value);
/* Form Validation Starts */
var errorDisplay = document.getElementById('errorDisplay');
errorDisplay.style.display = 'block';
if (currentTyre.isEmpty()) {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please fill all the fields";
return false;
}
if (currentTyre.isZero()) {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please check your input fields. 0 is not valid";
return false;
}
/* Form Validation Finishes */
this.getElementsByClassName("output")[0].textContent = currentTyre.sidewall().toFixed(2);
this.getElementsByClassName("output")[1].textContent = currentTyre.width().toFixed(2);
this.getElementsByClassName("output")[2].textContent = currentTyre.diameter().toFixed(2);
this.getElementsByClassName("output")[3].textContent = currentTyre.circumference().toFixed(2);
this.getElementsByClassName("output")[4].textContent = currentTyre.reverseMile().toFixed(2);
if (newTyre.isEmpty() || newTyre.isZero())
return;
this.getElementsByClassName("output")[5].textContent = newTyre.sidewall().toFixed(2);
this.getElementsByClassName("output")[6].textContent = newTyre.width().toFixed(2);
this.getElementsByClassName("output")[7].textContent = newTyre.diameter().toFixed(2);
this.getElementsByClassName("output")[8].textContent = newTyre.circumference().toFixed(2);
this.getElementsByClassName("output")[9].textContent = newTyre.reverseMile().toFixed(2);
document.getElementById('diameterDifference').textContent = currentTyre.diameterDifference(newTyre);
}, false);

Categories

Resources