Javascript code running function more than once - javascript

So I'm trying to make an area calculator for a trapezoid using html and js. My code is shown below, but for some reason I am not getting correct answers out of this. I suspect that is because the code is running the function more than once, but I'm not really sure.
function solveArea() {
var base1, base2, height, area;
base1 = document.getElementById("base1").value;
base2 = document.getElementById("base2").value;
height = document.getElementById("height").value;
area = ((base1 + base2) / 2) * height;
document.getElementById("area").value = area;
}
<form>
<input id="base1" type="number" placeholder="Base 1">
<input id="base2" type="number" placeholder="Base 2">
<input id="height" type="number" placeholder="Height">
<input id="area" type="number" readonly="" placeholder="Area">
<input id="calculate" type="button" value="Calculate" onclick="solveArea()">
<input type="reset" value="Clear">
</form>

You can use parseInt
function solveArea(){
var base1, base2, height, area;
base1= parseInt(document.getElementById("base1").value, 10);
base2= parseInt(document.getElementById("base2").value, 10);
height= parseInt(document.getElementById("height").value, 10);
area = ((base1 + base2) / 2)* height;
document.getElementById("area").value = area;
}

document.getElementById().value is a string, so when you use the + operator it will concatenate the two operands. In your case, you should convert strings to numbers (e.g. with the Number function):
function solveArea() {
let base1 = Number(document.getElementById("base1").value);
let base2 = Number(document.getElementById("base2").value);
let height = Number(document.getElementById("height").value);
let area = (base1 + base2) / 2 * height;
document.getElementById("area").value = area;
}
<form>
<input id="base1" type="number" placeholder="Base 1">
<input id="base2" type="number" placeholder="Base 2">
<input id="height" type="number" placeholder="Height">
<input id="area" type="number" readonly placeholder="Area">
<input id="calculate" type="button" value="Calculate" onclick="solveArea()">
<input type="reset" value="Clear">
</form>

your code is not running multiple times,
the problem is when you do
base1= document.getElementById("base1").value;
base2= document.getElementById("base2").value;
console.log(base1+base2)
and base1 = 1 and base2 = 1
then the output will be
11
So you are receiving the value as a string so just convert it to the number and your code will work fine.
function solveArea(){
var base1, base2, height, area;
base1= document.getElementById("base1").value;
base2= document.getElementById("base2").value;
height= document.getElementById("height").value;
area = ((+base1 + +base2) / 2)*height;
document.getElementById("area").value = area;
}

If you parse the input values as numbers using either parseFloat or Number then you should be bale to perform the basic arithmetic operations you need. Without parsing these numbers they were being treated as strings. The issue with parseInt in this regard is that it would prevent you from using numbers such as 5.25 for input ~ it would be treated as 5...
function solveArea() {
var base1, base2, height, area;
base1 = Number(document.getElementById("base1").value);
base2 = Number(document.getElementById("base2").value);
height = Number(document.getElementById("height").value);
area = ((base1 + base2) / 2) * height;
document.getElementById("area").value = area;
}
<form>
<input id="base1" type="number" placeholder="Base 1">
<input id="base2" type="number" placeholder="Base 2">
<input id="height" type="number" placeholder="Height">
<input id="area" type="number" readonly="" placeholder="Area">
<input id="calculate" type="button" value="Calculate" onclick="solveArea()">
<input type="reset" value="Clear">
</form>

Related

I cannot get an output of my calculation in input field

I wanted to create a calculator to calculate an Area of a circle, but i think it neither gets a Radius input and also doesnt put the calculated result in input field.
Below is my JavaScript and HTML code:
function calculateAreaOfCirle(myRadious){
return myRadious * myRadious * Math.PI;
}
const Radious = document.getElementById("Radious").value;
document.getElementById('Area')[0].value = calculateAreaOfCirle();
calculateAreaOfCirle();
<form>
<label for="Radious">Radious*Radious</label>
<input type="text" id="Radious" name="Radious">
<label for="Pi">*Pi=</label>
<input type="text" id="Area" name="Area" placeholder="Area">
<button onclick="calculateAreaOfCirle(myRadious)">Calculate</button>
</form>
The issue you have is that you need to get the current radius value in your function, and when you get the value, it is a String, not a Number. You can either use parseInt or make your input type=number
function calculateAreaOfCirle(){
const myRadious = parseFloat(document.getElementById("Radious").value);
document.getElementById('Area').value = myRadious * myRadious * Math.PI;
}
//calculateAreaOfCirle();
<form>
<label for="Radious">Radious*Radious</label>
<input type="number" id="Radious" name="Radious">
<label for="Pi">*Pi=</label>
<input type="text" id="Area" name="Area" placeholder="Area">
<button type="button" onclick="calculateAreaOfCirle()">Calculate</button>
</form>

Getting User Input and Calculating Hypotenuse

The code below should calculate the Pythagorean theorem. However, if the user puts 3 and 4 in the input fields and presses the button, the result does not show up. Could you help me find what's wrong?
function compute(form){
A=eval(form.a.value)
B=eval(form.b.value)
with (Math){
C=sqrt(((pow(a,2)+pow(b,2))))};
form.result.value=C;
}
<form>
<pre>
This program will calculate the hypotenuse of a triangle
Side 1 <input type="text" name="a" size=15>
Side 2 <input type="text" name="b" size=15>
Hypotenuse <input type="text" name="result" size=15>
<input type="button" value="calculate" onclick="compute(this.form)">
</pre>
</form>
Javascript is case sensitive, so after defining A one cannot access it by the lower case a.
Replacing A with a lower case a works
function compute(form) {
a = eval(form.a.value)
b = eval(form.b.value)
with(Math) {
C = sqrt(((pow(a, 2) + pow(b, 2))))
};
form.result.value = C;
}
<form>
<pre>
This program will calculate the hypotenuse of a triangle
Side 1 <input type="text" name="a" size=15>
Side 2 <input type="text" name="b" size=15>
Hypotenuse <input type="text" name="result" size=15>
<input type="button" value="calculate" onclick="compute(this.form)">
</pre>
</form>
You used a in the calcule instead of A, the variable you created before. Javascript is case sensitive, so var test is different of var Test.
In your case, just replace:
with (Math){
C=sqrt(((pow(a,2)+pow(b,2))))};
To this:
with(Math){
var C = sqrt( ( (pow(A ,2)+pow(B, 2)) ) );
};
Also, you should search how to organize your codes, thats make these simplier error easy to fix and avoid.
<!DOCTYPE HTML>
<html>
<body>
<form>
<pre>
This program will calculate the hypotenuse of a triangle
Side 1 <input type="text" name="a" size=15>
Side 2 <input type="text" name="b" size=15>
Hypotenuse <input type="text" name="result" size=15>
<input type="button" value="calculate" onclick="compute(this.form)">
</pre>
</form>
<script>
function compute(form){
var A = eval(form.a.value);
var B = eval(form.b.value);
with(Math){
var C = sqrt( ( (pow(A ,2)+pow(B, 2)) ) );
};
form.result.value = C;
}
</script>
</body>
</html>

Percentage calculator outputting integer only

I have a working percentage calculator (As demonstrated below). The 1st Input is for the inital number, the 2nd input is for the percentage and the 3rd outputs the answer.
I am trying to get the answer displayed in the 3rd input field as an integer (whole number only). What JS is needed to achieve this and to show the value in the input field?
<input type="number" class="input" id="without-visitors">
<input type="number" class="input" id="without-conversion">
<input type="number" class="input" id="without-formfillenquiries" readonly>
<script>
$('#without-visitors, #without-conversion').change(function() {
var withoutvisitors = parseFloat($('#without-visitors').val())
var withoutconversion = parseFloat($('#without-conversion').val())
var withoutformfillenquiries = parseFloat($('#without-formfillenquiries').val())
$('#without-formfillenquiries').val(withoutvisitors * withoutconversion / 100);
});
</script>
I added the Math.round() function to the last line - $('#without-formfillenquiries').val(withoutvisitors * withoutconversion / 100); in order to round the result to the nearest whole integer.
$('#without-visitors, #without-conversion').change(function() {
var withoutvisitors = parseFloat($('#without-visitors').val())
var withoutconversion = parseFloat($('#without-conversion').val())
var withoutformfillenquiries = parseFloat($('#without-formfillenquiries').val())
$('#without-formfillenquiries').val(Math.round(withoutvisitors * withoutconversion / 100));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="input" id="without-visitors">
<input type="number" class="input" id="without-conversion">
<input type="number" class="input" id="without-formfillenquiries" readonly>

Using parantheses around variables in Javascript to change priority in math calculations

I'm exercising in javascript calculations using a combination of maths and variables and i'm finding a difficulty on using the right way parentheses. For example i want to do the following calculation [(4,95/ans2)-4,5]*100 where ans2 is a calculated variable. In the last field i get 45.000 and i should take - 4.046 ... if the input in the first and second fields was 2 + 2
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<input type="text" name="ans3" size="35" id="ans3" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
/* in the following line i can't figure how to use with a proper way parentheses to prioriterize the calculations with the way i mentioned in the example before the code snippet*/
document.getElementById('ans3').value = [( 4.95 / parseInt(document.getElementById('ans2').value)) - 4.5] * 100;
}
</script>
The issue was in this row: document.getElementById('ans3').value = [( 4.95 / parseInt(document.getElementById('ans2').value)) - 4.5] * 100;. You need to use () instead of [] for grouping and you also don't need to parseInt the value. Here is the working snippet:
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
/* in the following line i can't figure how to use with a proper way parentheses to prioriterize the calculations with the way i mentioned in the example before the code snippet*/
document.getElementById('ans3').value = ((4.95 / document.getElementById('ans2').value) - 4.5) * 100
}
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<input type="text" name="ans3" size="35" id="ans3" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>

calculate values using entered formula

This is my html code:
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save">
Here the user enter formula value dynamically like R1+R2, (R1-R2)*100. I need to calculate final value using the formula.
Ex: If user enter value in formula field R1+R2; I need the result 300.
How do I calculate the value dynamically?
Check out this snippet, should work with any combo:
function calExpression() {
var f = document.getElementById('formula');
var inps = document.getElementsByTagName('input');
var expression = f.value.toUpperCase();//' '+f.value.replace(/([-\/\+\(\)])/g,' $1 ')+' ';
for (var i = 0; i < inps.length; i++) {
if (inps[i].id && inps[i].type && inps[i].type.toLowerCase() === 'text') {
expression = expression.replace(new RegExp('\\b'+inps[i].id+'\\b', 'ig'), inps[i].value);
}
}
eval('f.value = '+expression+';');
}
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calcExpression()">
You can use eval. This is the fastest and easiest solution, but you must be careful with it and check with regexp that formula has only R1, R2, (, ) and math operators in it.
Or (better solution) you can find a library to parse expressions, in example http://mathjs.org/docs/expressions/parsing.html
<input type="button" id="save" value="save" onclick="return calculate()">
<script>
function calculate() {
var val1 = document.getElementById('R1').value;
var val2 = document.getElementById('R2').value;
var result = +val1 + +val2;
document.getElementById('formula').value = result;
}
</script>
Because a problem occures with "+" you have to use +val1 + +val2
Infix to Prefix Conversion Algorithm:
Infix to Prefix Conversion
Prefix Evaluation Algorithm:
Prefix Evaluation Algorithm
Use help from these links.
You can use .eval() method which allow you to evaluates JavaScript code represented as a string. It's a really powerful method.
Then, you have to parse your formula. With this piece of code, you will be able to add expression like ((R1+R2) - (R1*3)) + 1 for example.
function calculate(){
var valid = true;
var regex = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]"'!&<>^\\?:])/ig;
var formula = document.querySelector('#formula').value;
var R1 = parseInt(document.querySelector('#R1').value);
var R2 = parseInt(document.querySelector('#R2').value);
formula = formula.replace(/R1/g, R1).replace(/R2/g,R2);
formula = formula.replace(regex, function (elm) {
return Math.hasOwnProperty(elm)
? "Math."+elm
: valid = false;
});
if (valid)
alert(eval(formula));
}
Then add onlick event on save button :
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calculate()">
Here is the Working Plunker

Categories

Resources