Percentage calculator outputting integer only - javascript

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>

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>

Javascript code running function more than once

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>

Third box locked value JS

I am using an javascript function script in html to get the product of two input boxes into third.
HTML:-
<input type="text" class="form-control" id="inputBuyPrice" placeholder="0.0" name="price" oninput="calculate()">
<input type="text" class="form-control" id="inputBuyAmount" placeholder="0.0" name="amount" oninput="calculate()">
<input type="text" class="form-control" id="inputBuyTotal" placeholder="0.0" name="total" oninput="calculate()">
And the javascript:-
<script>
function calculate() {
var myBox1 = document.getElementById('inputBuyAmount').value;
var myBox2 = document.getElementById('inputBuyPrice').value;
var result = document.getElementById('inputBuyTotal');
var numb = myBox1 * myBox2;
numb = numb.toFixed(8);
result.value = numb;
}
</script>
Now everything is working fine. But value of total gets locked by product of amount and price. I don't want it to be readonly but input that's value can be changed by user.
In a comment you've said:
Simple thing amount*price to be shown in total, but total can be changed manually and incase again price or amount change , product should be shown in total
If that's what you want, just remove the oninput="calculate()" on inputBuyTotal. That will allow the user to change it however they want, but then changing inputBuyPrice or inputBuyAmount will replace what they changed it to with the product of those fields.
(I wish the shops I buy from let me manually change the total amount to pay... 😉)
Change
oninput="calculate()"
to
oninput="calculateAmount()"
and add function calculateAmount()

form won't display value after calculation in javascript

i am trying to do some calculation but it does not seem to work.
I need to perform calculations on the data the user inputs and then display the results.
I don't seemed to be able to get the output for b and c. Is there a difference if i divide by a decimal/decimal?
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("energycost").value;
var y = document.getElementById("peak").value;
var z = document.getElementById("nonpeak").value;
var k = document.getElementById("input").value;
var b = x / (y + (z / k));
var c = b / k;
document.convert.output1.value = b;
document.convert.output2.value = c;
}
</script>
<body>
<FORM ACTION="#" NAME="convert">
Step 1:<br>
Enter the Fixed Tariff cost($/kWh)
<input type="text" id="fixed"SIZE=6
onblur="multiply.call(this,this.form.elements.energyload.value,this.form.elements.fixed.value)">
Enter the Total Energy load value(kWh)
<input type="text" id="energyload"SIZE=6
onblur="multiply.call(this,this.form.elements.energyload.value,this.form.elements.fixed.value)">
<BR><BR>
Total Energy load cost($)
<input type="text" id="energycost"SIZE=6 DISABLED>
<BR><BR>
Step 2: <br>
Enter Total Peak Energy load value(kWh)
<input type="text" id="peak"SIZE=6>
Enter Total Non-Peak Energy load value(kWh)
<input type="text" id="nonpeak"SIZE=6>
<BR><BR>
Step 3:<br>
Enter K value
<input type="text" id="input"SIZE=4
ONKEYUP="myFunction()">
<BR><BR>
<input type="text" id="output1" DISABLED>
TOU Peak Price
<input type="text" id="output2" DISABLED>
TOU Non-Peak Price
</FORM></body>
I don't really see where your result comes from.
This could be the solution (though I didn't try it, keep me posted):
document.convert.output1.value = b
document.convert.output2.value = c
I'd parseInt() on those values or do some validation on the user input, and as pointy added,
document.convert.output1.value = b;

Subtract an integer from a calculated total

I've built a script to add quantities/units and generate a total that displays sales tax.
How can I get this calculator to recognise #discount and subtract it from the total before the GST (10% sales tax) is calculated and added?
Also, is it possible to generate the total when the page loads? Instead of a user having to press the 'Generate total' button?
HTML
<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>
<input type="button" value="Generate Total" onclick="total()" /><br><br>
Discount <input type="text" id="discount" name="discount" value="500"/><br><br>
Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />
JS
function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");
for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
continue;
}
total_value += parseFloat(all_others[i].value);
}
document.getElementById("units_total").value = (total_value).toFixed(1);
document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);
document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);
document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
Firstly, to get your function to execute on window load, wrap it in a load event:
window.onload = function() {
total();
}
Secondly, to get it to figure in discount, you just need to modify your variable a few times, but then when adding them together, make sure you parse them with .parseFloat():
if (document.getElementById('discount').value != '') {
var discount = document.getElementById('discount').value;
}
else {
var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);
document.getElementById("sub_total").value = sub_total;
document.getElementById("gst_total").value = gst;
document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);
DEMO
First of all, I suggest you to perform validation and computations both server side and client side. The first ensures security while the second improves the responsiveness of the UI.
Said that, you'd better introduce several support variables and perform computation on them. You should get the value from the elements you are interested into using getElementById and store it in variables.
Then you should perform computation on that variables and finally place the results in the elements you want to use to display them to the user.
To perform the operation when the page loads have a look at this.

Categories

Resources