Herons formula in javascript and html - javascript

I have to find the areas of a triangle using Heron's formula. I wrote this code but it is not calculating the area correctly.
For example I input sideA= 5, sideB= 4, sideC= 3 and the answer is supposed to be 6 but instead I get 72088
Can anybody help me fix this and explain why its happening?
function Triangle(sideA, sideB, sideC) {
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
this.semiP = ((this.sideA + this.sideB + this.sideC) / 2);
this.area = function() {
return (Math.sqrt(this.semiP * ((this.semiP - this.sideA) * (this.semiP - this.sideB) * (this.semiP - this.sideC))));
}
}
function calculate() {
var sideA = document.getElementById('sideA').value;
var sideB = document.getElementById('sideB').value;
var sideC = document.getElementById('sideC').value;
var myTriangle = new Triangle(sideA, sideB, sideC);
document.getElementById('results').innerHTML = "Area: " + myTriangle.area();
}
<p>
Enter length of side a <input type='text' id="sideA" />
<br>
<br> Enter length of side b <input type='text' id="sideB" />
<br>
<br> Enter length of side c <input type='text' id="sideC" />
<div id="results"></div>
<button type="button" onclick="calculate()">Calculate</button>

The problem that you are having is the sideA, B and C variables are all of type STRINGs and not anything numeric. There are a few different solutions, in my answer I chose to use parseFloat to allow you to have decimal points as input as well as whole numbers.
function Triangle(sideA, sideB, sideC) {
this.sideA = parseFloat(sideA);
this.sideB = parseFloat(sideB);
this.sideC = parseFloat(sideC);
this.semiP = ((this.sideA + this.sideB + this.sideC) / 2);
this.area = function() {
return (Math.sqrt(this.semiP * ((this.semiP - this.sideA) * (this.semiP - this.sideB) * (this.semiP - this.sideC))));
}
}
function calculate() {
var sideA = document.getElementById('sideA').value;
var sideB = document.getElementById('sideB').value;
var sideC = document.getElementById('sideC').value;
var myTriangle = new Triangle(sideA, sideB, sideC);
document.getElementById('results').innerHTML = "Area: " + myTriangle.area();
}
<p>
Enter length of side a <input type='text' id="sideA" />
<br>
<br> Enter length of side b <input type='text' id="sideB" />
<br>
<br> Enter length of side c <input type='text' id="sideC" />
<div id="results"></div>
<button type="button" onclick="calculate()">Calculate</button>

Related

What is the best way to access input in javascript?

function gener10k() {
let x = getRndInteger(10000, 100);
let x1 = getRndInteger(x, 10);
let x2 = x - x1;
let higherValue = numberToArray(x1);
const longiness_higher = higherValue.length;
let higherInput = document.getElementsByName("higher[]");
for (var i = 0; i < longiness_higher; i++) {
higherInput[i].value = higherValue[i].value;
}
alert('higherValue ' + x1 + ' ' + higherValue[0] + higherValue[1] + higherValue[2] + higherValue[3] + "higherInput " + higherInput[0] + higherInput[1].value + higherInput[2].value + higherInput[3].value);
}
function getRndInteger(max, min) {
return Math.floor(Math.random() * (max - min)) + min;
}
function getlength(number) {
return number.toString().length;
}
function numberToArray(number) {
let array = number.toString().split("");
return array.map(x => parseInt(x));
}
<body>
<div class="inputCoefs">
<div class="inputCoef1">
<input type="text" name="higher[]" class="coeficientsIn10000" />
<input type="text" name="higher[]" class="coeficientsIn10000" />
<input type="text" name="higher[]" class="coeficientsIn10000" />
<input type="text" name="higher[]" class="coeficientsIn10000" />
<input type="text" name="higher[]" class="coeficientsIn10000" />
</div>
<div class="output">
<button class="but" id="checkit" onclick="gener10k();">DO IT</button>
</div>
</div>
I expected to write particular digits to equivalent input array. But instead, I have undefined variables. What is the best way to write to input from an array?
let higherInput = document.getElementsByName("higer[]");
This statement gets an object.
let higherValue = numberToArray(x1);
This statement gets a number array.
In your for loop:
higherInput[i].value = higherValue[i].value;
In this statement, higherInput[i].value refer to your text box value,
but what's higherValue[i].value?
Just use higherValue[i].
You can use the statement below to see that higherValue[i] is a number.
console.log(typeof(higherValue[0]);

How to calculating time difference

I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.
I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.
var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");
function calc(){
var minutt1=Number(hour1)*60+Number(min1);
var minutt2=Number(hour2)*60+Number(min2);
var resultat=0;
resultat = Number(minutt1) - Number(minutt2);
document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>
I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".
You need to get the value of hour1, min1, hour2, and min2. You also don't have an element min2:
var hour1=document.getElementById("hour1").value;
var min1=document.getElementById("min1").value;
var hour2=document.getElementById("hour2").value;
var min2=document.getElementById("min2").value;
What your code was trying to do was multiply and subtract HTML elements (never a good idea).
var hour1 = document.getElementById("hour1").value;
var min1 = document.getElementById("min1").value;
var hour2 = document.getElementById("hour2").value;
var min2 = document.getElementById("min2").value;
function calc() {
var minutt1 = Number(hour1) * 60 + Number(min1);
var minutt2 = Number(hour2) * 60 + Number(min2);
var resultat = 0;
resultat = Number(minutt1) - Number(minutt2);
document.getElementById("result").innerHTML = "Time differance is:" + Number(resultat);
}
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>
Other answers are close, but you need to get the value of the inputs after you click the button
var hour1 = document.getElementById("hour1");
var min1 = document.getElementById("min1");
var hour2 = document.getElementById("hour2");
var min2 = document.getElementById("min2");
window.calc = function () {
var minutt1 = parseInt(hour1.value) * 60 + parseInt(min1.value);
var minutt2 = parseInt(hour2.value) * 60 + parseInt(min2.value);
var resultat = minutt1 - minutt2;
document.getElementById("result").innerHTML = "Time differance is:" + resultat;
console.log({minutt1:minutt1,minutt2:minutt2,resultat:resultat,
hour1:hour1,min1:min1,
hour2:hour2,min2:min2
})
};
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>

Getting Cm to ft values and displaying in other element gives reference error

I have the conversion math correct(looked it up here), but getting the value from the element that displays the height in cm, then parse it to ft/inch and display it on(on click) the right hand span does not work, i get a reference error(converter not defined).
I cannot figure out why it is undefined, is it because of hoisting or can the parseInt function not have the parameters as they are?
Here is the function
var displayInches = document.getElementById("heightInches");
displayInches.addEventListener("click", function() {
toFeet(converter);
});
function toFeet(converter) {
var heightOutputCM = document.getElementById("yourHeight");
var converter = parseInt(heightOutputCM.value);
var realFeet = converter * 0.3937 / 12;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
return feet + "and" + inches;
}
Here is the link:
https://codepen.io/damianocel/pen/ZyRogX
HTML
<h1>Alcohol blood level calculator</h1>
<fieldset>
<legend>Your Indicators</legend><br>
<label for="height" class="margin">Height:</label>
<span class="leftlabel" id=""><span id="yourHeight"></span>Cm</span>
<input type="range" id="UserInputHeight" name="height" min="0" max="200" step="1" style="width: 200px">
<span id="heightInchesSpan" class="rightlabel"><span id="heightInches"></span>Ft</span>
<br>
<label for="" class="margin">Gender:</label>
<span class="leftlabel">Male</span>
<input type="range" id="salary" name="salary" min="0" max="1" style="width: 200px">
<span class="rightlabel">Female</span>
</fieldset>
JS
// get and display height
var displayHeightInput = document.getElementById("UserInputHeight");
displayHeightInput.addEventListener("input", function() {
sliderChange(this.value);
});
function sliderChange(val) {
var heightOutput = document.getElementById("yourHeight");
heightOutput.innerHTML = val;
toFeet();
return val;
}
function toFeet() {
var heightOutputCM = document.getElementById("yourHeight");
var converter = parseInt(heightOutputCM.innerHTML);
var realFeet = converter * 0.3937 / 12;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
document.getElementById("heightInches").innerHTML=feet + "and" + inches;
return feet + " and " + inches;
}

NaN error on form submission [duplicate]

This question already has answers here:
Reading numbers from inputs with JavaScript always returns NaN
(8 answers)
Closed 7 years ago.
I'm attempting to write a simple JavaScript program that calculates the cost of gas based on some parameters from a form. Upon form submission, I get a NaN error inside of the "calculatedMonthlyCost" div.
Can anybody tell me what I'm doing wrong? Is there a better way of doing this?
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
<script>
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
var userCostOfGas = document.forms[0].costOfGas.value;
var userMPG = document.forms[0].vehicleMPG.value;
var userNumMiles = document.forms[0].numMiles.value;
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
</script>
You were getting the values on page load (when they were empty). You just need to get the values inside the onsubmit event listener, and to convert them to Numbers.
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
If you only want 2 decimals, you can change this line:
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
Demo:
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
You save the value of your inputs before the onsubmit method is called. This actually saves a blank value since the variables are set before the user inputs a value and it's not dynamic. The values need to be checked on submit.
document.forms[0].onsubmit = function(e) {
var userCostOfGas = parseInt(document.forms[0].costOfGas.value,10);
var userMPG = parseInt(document.forms[0].vehicleMPG.value,10);
var userNumMiles = parseInt(document.forms[0].numMiles.value,10);
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};

Simple conversion of temperature program

I have a program that converts temperature, but for some reason I can't figure out why the result isn't printing out when I click my button. Any help would be appreciated. Here is my code:
var report = function(celsius, fahrenheit) {
document.getElementById("result").innerHTML = (celsius + "\xbOF="
fahrenheit + "\xbOF");
};
document.getElementById("f_to_c").onclick = function() {
var f = document.getElementById("temperature").value;
report((f - 32) / 1.8, f);
};
document.getElementById("c_to_f").onclick = function() {
var c = document.getElementById("temperature").value;
report(c, 1.8 * c + 32);
};
<title>HW problem 3</title>
<h1>Temperature Conversion</h1>
<p>
<input type="number" id="temperature" />
<button id="f_to_c">F to C</button>
<button id="c_to_f">C to F</button>
</p>
<p id="result"></p>
I apologize for asking a basic question. I have another script that calculates tip and it works fine, so I can't figure out what isn't working here. Thanks
Aside from the missing plus sign in your report function, the escape strings for your degree (°) sign need to be capitalized in order to work properly (i.e. \xB0 instead of \xb0). Here is a working example:
var report = function(celsius, fahrenheit) {
document.getElementById("result").innerHTML = (celsius + "\xB0C = " + fahrenheit + "\xB0F");
};
document.getElementById("f_to_c").onclick = function() {
var f = document.getElementById("temperature").value;
report((f - 32) / 1.8, f);
};
document.getElementById("c_to_f").onclick = function() {
var c = document.getElementById("temperature").value;
report(c, 1.8 * c + 32);
};
<title>HW problem 3</title>
<h1>Temperature Conversion</h1>
<p>
<input type="number" id="temperature" />
<button id="f_to_c">F to C</button>
<button id="c_to_f">C to F</button>
</p>
<p id="result"></p>

Categories