Calculate with formula javascript - javascript

Lately i want to make a converter formula with javascript. but i got a stack at this function
javascript
function UconverterDP(){
var inputD = document.getElementById('inputD').value;
var inputP = document.getElementById('inputP').value;
jikaP = inputD * 0.4;
bagianatasU1 = 0.8 * inputP * inputD;
bagianbawahU1 = P + (0.4 * inputD);
hasilU1 = bagianatasU1 / bagianbawahU1;
bagaianatasU2 = 0.8 * inputD;
bagaianatasU2a = 1 - bagaianatasU2 ;
bagaianatasU2h = inputP - bagaianatasU2a;
bagianbawahU2 = 0.0114 * inputP;
bagianbawahU2a = Math.pow(bagianbawahU2, 1.7);
bagianbawahU2b = 0.92 * bagianbawahU2a;
bagianbawahU2h = bagianbawahU1 * bagianbawahU2b;
hasilU2 = bagaianatasU2h / bagianbawahU2h;
if (inputP <= jikaP) {
document.getElementById("outputU").innerHTML = Hasil U1;
} else {
document.getElementById("outputU").innerHTML = hasilU2;
}
}
this my input
<tr>
<td>
<label>D : </label>
<input id="inputD" type="number" onchange="UconverterDP()">
</td>
<td>
<label>P : </label>
<input id="inputP" type="number" onchange="UconverterDP()" >
</td>
</tr>
and this output
<label> BUI (U): </label>
<span id="outputU"></span>
And this is the formula:

i really don t know if this is what are you searching, if it isn't tell me what is missing (and explain me a little bit more your idea):
<script>
function UconverterDP(){
var inputD = document.getElementById('inputD').value;
var inputP = document.getElementById('inputP').value;
jikaP = inputD * 0.4;
if (inputP <= jikaP) { // here your program choose what formula will use
var u =(0.8*inputP*inputD)/(inputP+0.4*inputD)// here is the first formula
document.getElementById("outputU").innerHTML = u;// and then here you return the value that you want
}
else {
var u = inputP-((1-0.8*inputD)/(inputP+0.4*inputD))/(0.92*0.0114*(inputP**1.7))// and here is the second formula
document.getElementById("outputU").innerHTML = u;// here is the same you return the value
}
}
// maybe you can do more short this code putting together the two "document.getElementById("outputU").innerHTML = u;" here, but work in this way also
</script>

Related

How do I use an input to define decimals for other inputs?

I am trying to set the number of decimals of many inputs by using a specific input.
Here is what I am doing:
window.oninput = function(event) {
var campo = event.target.id;
// DECIMALS
if (campo == "decimalTemp") {
var i = decimalTemp.value;
ºC.value.toFixed = i;
ºK.value.toFixed = i;
ºF.value.toFixed = i;
ºRa.value.toFixed = i;
}
// TEMPERATURE
if (campo == "ºC") {
ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
} else if (campo == "ºK") {
ºC.value = (ºK.value * 1 - 273.15).toFixed(2);
ºF.value = (ºK.value * 1.8 - 459.889).toFixed(2);
ºRa.value = (ºK.value * 1.8).toFixed(2);
} else if (campo == "ºF") {
ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(2);
ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(2);
ºRa.value = (ºF.value * 1 + 459.67).toFixed(2);
} else if (campo == "ºRa") {
ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(2);
ºK.value = (ºRa.value / 1.8).toFixed(2);
ºF.value = (ºRa.value * 1 - 459.67).toFixed(2);
}
};
<h3>Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> <small>Decimals<small></h3>
Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">
<br> Kelvin (K) <input id="ºK" type="number" min="0" value="293">
<br> Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">
<br> Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">
In summary, I would like to know if this construction is correct:
var i = decimalTemp.value;
ºC.value.toFixed = i;
I already tried something like:
ºC.value.toFixed(i);
But didn't work. Any idea where am I wrong?

Sharing random variables between functions

I'm trying to code a game and part of it has a combat system. I want the player to click a button as many times as they want to find an opponent, then to click the attack button when they find one they like and a timed event happens to slowly reveal the result.
The problems I'm coming against are:
- If the VAR are outside the functions, then you can only infiltrate once, but if it's inside the first function then the other ones can't use those values for the battle.
- The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Thank you very much for looking and I appreciate the help!
Javascript:
var titles = ["Peasant", "Knight"];
var first = ["Ada", "Adro", "Ama"];
var last = ["nija", "har", "nake"];
var random_name1 = titles[Math.floor(Math.random() * titles.length)] + ' ' + first[Math.floor(Math.random() * first.length)] + last[Math.floor(Math.random() * last.length)];
var random_acres1 = (max_acres * (Math.floor(Math.random() * (140 - 75)) + 75) / 100).toFixed(0);
var random_troops1 = (random_acres1 * (Math.floor(Math.random() * (1500 - 600)) + 600) / 100).toFixed(0);
var random_off1 = (random_troops1 * (Math.floor(Math.random() * (1200 - 400)) + 400) / 100).toFixed(0);
var combat_victory_acres1 = (random_acres1 * (((Math.random() * (35 - 11)) + 11) / 100)).toFixed(0);
var combat_defeat_acres1 = (random_acres1 * (Math.floor(Math.random() * (20 - 11)) + 11) / 100).toFixed(0);
var text_victory = 'You have been awarded with ';
var text_defeat = 'You have lost control of ';
var text_acres = ' acres.';
function infiltrate(){
var x = document.getElementById("Combat_table");
if (x.style.display === "none") {
x.style.display = "block";
}
document.getElementById('combat_army_strength').innerHTML = army_strength;
document.getElementById('combat_max_acres').innerHTML = max_acres;
document.getElementById('random_name1').innerHTML = random_name1;
document.getElementById('random_acres1').innerHTML = random_acres1;
document.getElementById('random_troops1').innerHTML = random_troops1;
document.getElementById('random_off1').innerHTML = random_off1;
};
function attack_random1(){
document.getElementById("attack_button1").style.display="none";
document.getElementById("infiltration").style.display="none";
var y = document.getElementById("Combat_Results");
if (y.style.display === "none") {
y.style.display = "block";
}
setTimeout(Combat_Text4, 5000)
var final_outcome1 = army_strength - random_off1;
if (final_outcome1 >= 0) {
setTimeout(Combat_Text_Victory1, 6000);
} else {
setTimeout(Combat_Text_Defeat1, 6000);
}
};
function Combat_Text4() {
document.getElementById("Combat_Results4").innerHTML = "The battle is over, a scout is dispatched to you with the results.";
}
function Combat_Text_Victory1() {
max_acres = max_acres + combat_victory_acres1;
var text_victory_1 = text_victory + combat_victory_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You achieved <b>Victory!</b>";
document.getElementById("Combat_Results6").innerHTML = text_victory_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
function Combat_Text_Defeat1() {
max_acres = max_acres - combat_defeat_acres1;
var text_defeat_1 = text_defeat + combat_defeat_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You have been <b>Defeated!</b>";
document.getElementById("Combat_Results6").innerHTML = text_defeat_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
HTML:
<div id="Combat" class="tabcontent">
Total Land: <span id="combat_max_acres">10</span><br>
Total Offense: <span id="combat_army_strength">0</span><p>
<button id="infiltration" onclick="infiltrate()">Infiltrate Kingdoms</button>
<div id="Combat_table" style="display: none">
<center><table>
<tr valign="center">
<th>Kingdom Name</th>
<th>Acres</th>
<th>Troop <br>Numbers</th>
<th>Total <br>Offense</th>
<th></th>
</tr>
<tr id="combat_row1">
<td><span id="random_name1"></span></td>
<td><span id="random_acres1"></span></td>
<td><span id="random_troops1"></span></td>
<td><span id="random_off1"></span></td>
<td><button onclick="attack_random1()" id="attack_button1">Attack!</button></td>
</tr>
</table>
</div>
<br>
<div id="Combat_Results" style="display: none">
<center><table><tr>
<td><center><span id="Combat_Results4"></span></td>
</tr><tr>
<td><center><span id="Combat_Results5"></span></td>
</tr><tr>
<td><center><span id="Combat_Results6"></span></td>
</tr>
</table>
</div>
The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Use Math.round instead of Number#toFixed, because for addition numerical values, you need both operands as number, not a string.
Use toFixed only for displaying a number.
For the other parts, I suggest to use an object with arrays for same items, like
{
name: [],
acres: [],
troops: [],
off: [],
victory_acres: [],
combat_defeat_acres: [],
// etc.
}

javaScript got stuck with converting bytes

so I've got a bit of the problem. I am trying to make a function in wich : human clicks on input box with mouse and types some random numbers in bytes and that number should be convert and shown in two other boxes such as MegaBytes and KiloBytes. So my problem is that Javascript shows me error :
Cannot set property 'value' of null
at convert (script.js:7)
at HTMLInputElement.onkeyup
here is my code so far:
function convert(inputas)
{
var i;
if(inputas == "B")
{
i = document.getElementById("baitas").value / 1000;
document.getElementById("kiloBaitas").value = i;
}
else if(inputas == "KB")
{
i = document.getElementById("kiloBaitas").value * 1024;
document.getElementById("baitas").value = i.toFixed(2);
}
}
HTML code:
<input type="text" id="baitas" onkeyup="convert('B')placeholder="Bits">
<input type="text" id="kilobaitas"
`onkeyup="convert('KB')"placeholder="Kilobits">
<input type="text" id="megabaitas" onkeyup="convert('MB')"
placeholder="Mbits">
<script src="script.js"></script>
when comparing your javascript with the html. the kilobaitis element is not spelt with a consistent case.
JavaScript is case sensitive.
function convert(inputas) {
var i;
if (inputas == "B") {
i = document.getElementById("baitas").value / 1000;
document.getElementById("kilobaitas").value = i;
} else if (inputas == "KB") {
i = document.getElementById("kiloBaitas").value * 1024;
document.getElementById("baitas").value = i.toFixed(2);
}
}
<input type="text" id="baitas" onkeyup="convert('B')" placeholder=" Bits ">
<input type="text " id="kilobaitas" onkeyup="convert('KB')" placeholder="Kilobits ">
<input type="text " id="megabaitas" onkeyup="convert('MB')" placeholder="Mbits ">
(function() {
var elems = [],
elemsId = ['baitas','kilobaitas','megabaitas'];
function fix(a){ return ( a * 100 | 0 ) / 100 }
function convert(inputas)
{
var i;
switch(inputas)
{
case 0:
i = elems[0].value;
elems[1].value = fix( i / 1024 );
elems[2].value = fix( i / 1048576 );
break;
case 1:
i = elems[1].value;
elems[0].value = i * 1024;
elems[2].value = fix( i / 1024 );
break;
case 2:
i = elems[2].value;
elems[0].value = i * 1048576;
elems[1].value = i * 1024;
break;
}
}
for (var i=0; i < elemsId.length; i++)
{
elems[i] = document.getElementById( elemsId[i] );
elems[i].addEventListener('keyup', convert.bind(null, i) )
}
}());
<input type="text" id="baitas" placeholder=" Bits">
<input type="text" id="kilobaitas" placeholder=" Kilobits">
<input type="text" id="megabaitas" placeholder=" Mbits">

Improving Secure Password Generator

Simple Password Generator Example:
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOP" +
"1234567890" +
"#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/",
pass = "",
PL = 10;
for (var x = 0; x < PL; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword();
}
<form name="myform" method="post" action="">
<table width="100%" border="0">
<tr>
<td>Password:</td>
<td>
<input name="row_password" type="text" size="40">
<input type="button" class="button" value="Generate" onClick="generate();" tabindex="2">
</td>
</tr>
</table>
</form>
Improving Functionality Questions
1). Obtaining All Values Within Variable
Taking the base script above, how can I call chars.length and chars.charAt(i) where chars equals all the values within Chars?
var Chars = {};
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
2). Implementing a checkbox system for less advanced password
To generate a less advanced password, such as not including symbox via unchecking a checkbox, how can I make it so only Chars.abc, Chars.ABE, and Chars.Num values are used?
3). Equally Divide Password Length By Chars
Round down (Password length / Chars used ), ie; the example used in this question generates a 10 character password and uses all charecters, therefore there would be a minimum of 2 of each Chars.
The 3rd functionality is missing and will probably be way more sophisticated. But this is a simple solution to the 1st and 2nd ones.
var output = document.getElementsByTagName('output')[0];
var Chars = {};
Chars.length = 16;
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.NumRequired = true;
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
var generator = new randomPasswordGenerator(Chars);
var simpleGenerator = new randomPasswordGenerator({
length: 6,
abc: 'abc',
Num: '0'
});
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', clickFunction);
var checkbox = document.getElementsByTagName('input')[0];
function clickFunction () {
if (checkbox.checked) output.textContent = simpleGenerator.randomPassword();
else output.textContent = generator.randomPassword();
}
function randomPasswordGenerator(opts) {
for(var p in opts) this[p] = opts[p];
this.randomPassword = randomPassword;
}
function randomPassword() {
var chars = (this.abc || "") +
(this.ABE || "") +
(this.Num || "") +
(this.Sym || ""),
pass = [],
PL = this.length;
if (this.NumRequired) {
var r = Math.floor(Math.random() * this.Num.length);
var i = Math.floor(Math.random() * PL);
pass[i] = this.Num[r];
}
for (var x = 0; x < PL; x++) {
if(!pass[x]) {
var i = Math.floor(Math.random() * chars.length);
pass[x] = chars.charAt(i);
}
}
return pass.join('');
}
output {
margin: 12px;
display: block;
border-bottom: 1px solid
}
<button>Generate</button>
<input type="checkbox">Simple
<output></output>

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