Calculating multiple inputs value with javascript - javascript

i'm having trouble going trough making a calculator (sum only) of 5 inputs fields in html/javascript and i can't manage to find what's wrong in my code
i tried messing around with types such as int instead of var and passing the value into parseInt, i somehow managed to have a result like "11111" where it should be like "5" but alongside that case the result is never printed in the innerHTML even after i added the "if not null" condition
Here is my html
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute();">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
and here is my javascript
function ratingCompute()
{
var designValue = document.getElementById("design").value;
var plotValue = document.getElementById("plot").value;
var charValue = document.getElementById("character").value;
var enjoyValue = document.getElementById("enjoyment").value;
var musicValue = document.getElementById("music").value;
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
Any clue?

JavaScript is not a type variable language try using let or const. And here is how you properly parse it. If you did it already then its because of your variable declaration.
let designValue = parseInt(document.getElementById("design").value);
let plotValue = parseInt(document.getElementById("plot").value);
let charValue = parseInt(document.getElementById("character").value);
let enjoyValue = parseInt(document.getElementById("enjoyment").value);
let musicValue = parseInt(document.getElementById("music").value);

In javascript you should use keyword var/let/const instead of int. and you have to convert String type input value to int using parseInt method.
Please check this:
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute()">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>

As mentioned by #Joshua Aclan, JavaScript does not have an "int" variable declaration, only "var". Also you have to cast all of the inputs to int or float, because otherwise you are adding strings and the values of input fields are always strings. Also the output is most likely empty because int designValue... produces an error.
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}

Related

How do i clear multiple user inputs in javascript

I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything.
i want to make the reset button to clear user inputs?
Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong.
Please i'll appreciate if anyone can assist me with this.
<div class=" DTRloading__form" style="display: block;">
<div class="form-container">
<div class="info">
</div>
<form class="form-inline">
<div class="form-group w-5 ">
<label for="red">Red Phase:</label>
<input type="number" class="form-control formInline" id="red" style="width: 80px">
</div>
<div class="form-group">
<label for="yellow">Yellow Phase:</label>
<input type="number" class="form-control formInline" id="yellow" style="width: 80px">
</div>
<div class="form-group">
<label for="blue">Blue Phase:</label>
<input type="number" class="form-control formInline" id="blue" style="width: 80px">
</div>
<div class="form-group">
<label for="neutral">Neutral:</label>
<input type="number" class="form-control formInline" id="neutral" style="width: 80px">
</div>
</form>
<label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label>
<input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required>
<button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button>
</div>
<div class="output">
<h5 class="b-display">DTR Full Load Current is:</h5>
<div id="flA" class="form-control bill"></div>
<h5 class="b-display">The percentage Loading of this DTR is:</h5>
<div id="outputLoading" class="form-control bill"></div>
<!-- <div id="outputSum" class="form-control bill"></div>-->
<button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button>
</div>
</div>
<script>
document.getElementById("btnStart3").addEventListener('click', doCalc);
function doCalc() {
// Assign user inputs to variables
let x = parseFloat(document.querySelector("#red").value);
let y = parseFloat(document.querySelector("#yellow").value);
let z = parseFloat(document.querySelector("#blue").value);
let n = parseFloat(document.querySelector("#neutral").value);
const capacity = document.querySelector("#inputKVA");
const output2 = document.querySelector("#outputLoading");
const output3 = document.querySelector("#flA");
const start3 = document.getElementById("btnStart3");
const refresh3 = document.getElementById("btnRefresh3");
// // Call the average function
getAverage(x,y,z,n);
}
function getAverage(x,y,z,n) {
// Calculate the average
let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100);
// Display result to user
console.log(average);
outputLoading.innerHTML = average.toFixed(0) + "%";
//
}
const capacity = document.querySelector("#inputKVA");
function calculate(e) {
console.log(e);
e.preventDefault();
console.log("btnStart3 clicked");
var totalfLA = ((capacity.value * 1000) / (1.7321 * 415));
console.log(totalfLA);
flA.innerHTML = totalfLA.toFixed(1) + "A";
}
function emptyInput() {
console.log("emptied!");
outputKVA.innerHTML = "";
flA.innerHTML = "";
x.value = "";
y.value = "";
z.value = "";
n.value = "";
capacity.value = "";
output2.value = "";
output3.value = "";
}
btnStart3.addEventListener("click", calculate);
refresh3.addEventListener("click", emptyInput);
</script>
You can try in html with below button type as well.
<input type="reset" value="Reset">
If you want reset form from javascript then
document.getElementById("your-form-id").reset();
Change
1. <form class="form-inline">
2. refresh3.addEventListener("click", emptyInput);
to
1. <form class="form-inline" id="form">
2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput);
3. function emptyInput() {
document.getElementById("form").reset();
}

Storing variable from calculated inputs - javascript

Welcome ! I have a question. Is the any possibility to store calculated data from three inputs for further math calculations? My clue is to store this dowform.value after calculations in new variable so i could for example divide this calculated value or multiply it and get new value. Code below for better understanding:
Javascript:
function dryOperatingWeight() {
const bew = document.getElementById("bew").value;
const crew = document.getElementById("crew").value;
const pantryDiv = document.getElementById("pantry").value;
let arr = document.getElementsByName("dow");
let tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) tot += parseInt(arr[i].value);
}
dowform.value = tot;
}
HTML:
<div class="form-group">
<label for="bew">Basic Empty Weight</label>
<input class="form-control" name="dow" type="text" id="bew" value="" onkeyup = "dryOperatingWeight()"/>
</div>
<div class="form-group">
<label id="crew"> Crew Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="crew"
value=""
placeholder="crew weight"
onkeyup = "dryOperatingWeight()"
/>
<div class="form-group">
<label id="pantry">Pantry Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="pantry"
placeholder="Enter pantry code"
onkeyup = "dryOperatingWeight()"
/>
</div>
<div class="form-group">
<label id="pantry">Water Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="water"
placeholder="Enter water weight"
onkeyup = "dryOperatingWeight()"
/>
</div>
<div id="dow">
<div class="form-group">
<label for="dryoperating weight">Dry Operating Weight</label>
<input class="form-control" type="number" id="dowform" readonly/>
</div>
</div>
You can declare your variable outside of the function and just reuse it and modify it as needed.
let dow;
function dryOperatingWeight() {
const bew = document.getElementById("bew").value;
const crew = document.getElementById("crew").value;
const pantryDiv = document.getElementById("pantry").value;
let arr = document.getElementsByName("dow");
dow = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) dow += parseInt(arr[i].value);
}
dowform.value = dow;
}

Why im i getting NaN when using parseINt or undefined?

I'm getting NaN despite using parseInt or .value, and I don't understand why is that. I also tried changing the code, but then im getting undefined.
As a beginner I don't get what I'm doing wrong despite it being so simple. Any tips?
const btn = document.querySelector('.btn');
btn.addEventListener('click',calcWinner);
function calcWinner(e){
const powerG = document.querySelector('#power-g');
const techG = document.querySelector('#tech-g');
const chanceG = document.querySelector('#chance-g');
const powerF = document.querySelector('#power-f');
const techF = document.querySelector('#tech-f');
const chanceF = document.querySelector('#chance-f');
let gokuR = parseInt(powerG + techG + chanceG)
let friezeR = parseInt(powerF.value) + parseInt(techF.value) + parseInt(chanceF.value);
console.log(parseInt(gokuR.value));
}
<body>
<div class="container">
<div class="goku">
<h2>Battle chance</h2>
<form action="">
<input type="number" name="" id="power-g" >
<label for="power-g">Power</label>
<input type="number" name="" id="tech-g" >
<label for="tech-g">Technique</label>
<input type="number" name="" id="chance-g" >
<label for="chance-g">Chance</label>
</form>
</div>
<div class="frieza">
<h2>Battle chance</h2>
<form action="">
<input type="number" name="" id="power-f" >
<label for="power-f">Power</label>
<input type="number" name="" id="tech-f" >
<label for="tech-f">Technique</label>
<input type="number" name="" id="chance-f" >
<label for="chance-f">Chance</label>
</form>
</div>
</div>
<h1 >Winner : <span class="winner"></span></h1>
CalcWinner
<script src="app.js"></script>
</body>
First, grab the value instead of the element, e.g. like this:
const powerG = document.querySelector('#power-g').value;
Then use either parseInt, Number or + to convert the String number to an actual number, and you will be able to calculate the result.
Stack snippet
const btn = document.querySelector('.btn');
btn.addEventListener('click',calcWinner);
function calcWinner(e){
const powerG = document.querySelector('#power-g').value;
const techG = document.querySelector('#tech-g').value;
const chanceG = document.querySelector('#chance-g').value;
const powerF = document.querySelector('#power-f').value;
const techF = document.querySelector('#tech-f').value;
const chanceF = document.querySelector('#chance-f').value;
let gokuR = Number(powerG) + Number(techG) + Number(chanceG);
let friezeR = parseInt(powerF) + parseInt(techF) + parseInt(chanceF);
console.log(gokuR);
console.log(friezeR);
}
<div class="container">
<div class="goku">
<h2>Battle chance</h2>
<form action="">
<input type="number" name="" id="power-g" >
<label for="power-g">Power</label>
<input type="number" name="" id="tech-g" >
<label for="tech-g">Technique</label>
<input type="number" name="" id="chance-g" >
<label for="chance-g">Chance</label>
</form>
</div>
<div class="frieza">
<h2>Battle chance</h2>
<form action="">
<input type="number" name="" id="power-f" >
<label for="power-f">Power</label>
<input type="number" name="" id="tech-f" >
<label for="tech-f">Technique</label>
<input type="number" name="" id="chance-f" >
<label for="chance-f">Chance</label>
</form>
</div>
</div>
<h1 >Winner : <span class="winner"></span></h1>
CalcWinner
Without the HTML it is hard to give you an accurate answer. But parseInt() is meant for a string. You are trying to use it on elements instead of strings. You need to get the value of the HTML element instead of the element itself.
Instead of:
const powerG = document.querySelector('#power-g');
You would need to do something like:
const powerG = document.querySelector('#power-g').value;
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

I have just formatted numbers to appear with commas but now my calculator doesn't work?

I am building a calculator, which I have previously asked questions on, see previous link: Building an interest rate calculator, however it won't produce figure
I want some fields to appear with commas when entered, I found some code on here and it seems to work with the formatting however now the calculations just return NaN.
Any ideas why adding commas would stop it from working?
Here's the code I used to add the commas and the code for the calculator is on the previous link:
HTML:
<div class="col-md-10 col-md-offset-1 form-body form-group">
<h2 class="form-heading">Find out how much your mortgage will cost</h2>
<div class="row text-muted">
<div class="col-md-5 col-md-offset-1 calc-input">
<h3>Purchase Price</h3>
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control comma" id="pp" placeholder="150,000" onchange="depositValue()">
</div>
<h3>Deposit</h3>
<div class="row text-muted">
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control" id="percent" placeholder="10" onchange="depositValue()">
<span class="input-group-addon">%</span>
</div>
</div>
<div class="col-md-8">
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control comma" id="dp" placeholder="15,000" onchange="depositPercent()">
</div>
</div>
</div>
<h3>Mortgage Term</h3>
<div class="input-group">
<input type="text" class="form-control" id="mt" placeholder="25">
<span class="input-group-addon">Years</span>
</div>
<h3>Interest Rate</h3>
<div class="input-group">
<input type="text" class="form-control" id="ir" placeholder="4">
<span class="input-group-addon">%</span>
</div>
</div>
<div class="col-md-5 text-center">
<h3>Estimated Monthly Payment:</h3>
<p id="result"></p>
</div>
</div>
<div class="row text-muted">
<div class="col-md-10 col-md-offset-1 text-center">
<button class="btn btn-cta" onclick="calculate()">Calculate</button>
</div>
</div>
</div>
Calculator JS:
function calculate() {
var pp = document.getElementById("pp").value;
var dp = document.getElementById("dp").value;
var mt = document.getElementById("mt").value;
var ir = document.getElementById("ir").value;
var result = document.getElementById("result");
var la = parseInt(pp.replace(/,/g, ""), 10) - parseInt(dp.replace(/,/g, ""), 10);
var intRate = (ir/100)/12;
var months = mt * 12;
var monthlyPayment = ((((la*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100).toFixed(2));
result.innerHTML = "£" + monthlyPayment.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function depositValue() {
var pp = document.getElementById("pp").value;
var percent = document.getElementById("percent").value;
var dp = document.getElementById("dp");
var dpValue = (parseInt(percent.replace(/,/g, ""), 10) / 100) * parseInt(pp.replace(/,/g, ""), 10);
dp.value = dpValue;
}
function depositPercent() {
var pp = document.getElementById("pp").value;
var dp = document.getElementById("dp").value;
var percent = document.getElementById("percent");
var dpPercent = (parseInt(dp.replace(/,/g, ""), 10) / parseInt(pp.replace(/,/g, ""), 10) * 100).toFixed(0);
percent.value = dpPercent;
}
Comma JS (in another file):
$('input.comma').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
The moment you add the commas, it's no longer a number, but a string. When you do your calculations you'll have to account for that by stripping them out before processing.

arithmatic using javascript

i'd like to ask how to do arithmatic using javascript
Here i have some input value
<div class="form-group">
<label for="exampleInputTotalBayar">Total Bayar</label>
<input type="text" class="form-control" id="inputTotalBayar" placeholder="Total Bayar" name="totalBayar" value="{{ $peminjaman->totalBayar }}">
</div>
<div class="form-group">
<label for="exampleInputJumlahBayar">Telah Membayar</label>
<input type="text" class="form-control" id="inputJumlahBayar" onchange="" placeholder="Jumlah Bayar" name="jumlahBayar" value="{{ $peminjaman->jml_bayar }}">
</div>
I have this input too
<div class="form-group">
<label for="exampleInputDenda">Denda</label>
<input type="text" class="form-control" id="exampleInputDenda" placeholder="Denda" name="denda" value="{{ $peminjaman->denda }}">
</div>
And this
<div class="form-group">
<label for="exampleInputBayarKembali">Jumlah Bayar Pengembalian</label>
<input type="text" class="form-control" id="inputBayarKembali" onchange="" placeholder="Bayar Pengembalian" name="bayarPengembalian">
</div>
And using javascript, the answer from arithmatic operation will be shown here
<p>Bayar Pengembalian: <div id="bayar" name="bayar"></div></p>
<p>Sisa: <div id="sisa" name="sisa"></div></p>
For Bayar Pengembalian, it work just fine. But when im trying to calculate Sisa, the answer wont be shown. Here is my javascript
$("#exampleInputDenda").change(function() {
var bayar = parseInt("0");
var totalBayar = parseInt($("#inputTotalBayar").val());
var jumlahBayar = parseInt($("#inputJumlahBayar").val());
var denda = parseInt($("#exampleInputDenda").val());
bayar = bayar + denda + totalBayar - jumlahBayar;
$("#bayar").html(bayar);
});
$("#inputBayarKembali").change(function() {
var sisa = parseInt("0");
var bayar = $("#bayar").val();
sisa = sisa + $("#inputBayarKembali").val()-bayar;
$("#sisa").html(sisa);
});
would you help me with my problem? I'm just in the middle of studying javascript and laravel, so i really need your help... thanks before
You need to parseInt() around the input values:
$("#inputBayarKembali").change(function() {
var sisa = parseInt("0");
var bayar = parseInt($("#bayar").text());
sisa = sisa + parseInt($("#inputBayarKembali").val())-bayar;
$("#sisa").html(sisa);
});

Categories