JavaScript Real Time Calculation - javascript

I have built a table with custom inputs numbers with jeditable. The Input type is gone once you put the value
I need to find a JavaScript Real Time Calculation which automatically makes the amount of my values.
I have found 2 interesting examples very suitable for my case but there is the possibility to achieve it the same without using the form and inputs?
First example
Second example

Yes, it is. As you know a div element can be accessed by document.getElementById('div_id') and its value can be accessed by document.getElementById('div_id').value.
So take out the form and insert an id for the div's that you need and access the value and then find the sum and then set the value as the sum to another div. Here is the code
<script>
function calculateBMI() {
var wtStr =document.getElementById('w').value;
if (!wtStr)
wtStr = '0';
var htStr = document.getElementById('h').value;
if (!htStr)
htStr = '0';
var weight = parseFloat(wtStr);
var height = parseFloat(htStr);
document.getElementById("r").value = weight + height;
}
</script>
<input id = "w" type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input id = "h" type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input id = "r" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
​and if you don't want input you can use textarea.

Related

JavaScript while loop won't increment properly for HTML document [duplicate]

Something that has bugged me for a while and always giving me headaches.
I have an input field with a value in numbers
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
I am picking up the value of the input field with
let charlife = document.getElementById('base-life');
I have a number with which i want to increase the value of the base-life input field. This of course changes dynamically based on other stuff but let's say it's 2
let increaseWith = 2;
in an onclick function i want to increase base-life with 2 (base-life + 2) everything it is clicked
function increase() {
charlife.value += increaseWith;
}
Now this only adds 2 to the value of the input field, makes it 202. I know that this happens when one of the numbers are actually strings. Perhaps my charlife. I tried everything and it gets worse. I tried parseInt(charlife.value) - no luck. I tried other methods but it doesn't work. And i only have this problem with input fields. When the element is just a or another simpler html element - it all works easier. Has to do with how JS parses input fields. Can someone shed some light?
let charlife = document.getElementById('base-life');
let increaseWith = 2;
function increase() {
value = parseInt(charlife.value);
value += increaseWith;
charlife.value = value;
}
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button onclick="increase()">Increase</button>
Here is the working snippet with some custom code that is according to your specifications
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button class="add" onclick="let increaseWith = 2;document.getElementById('base-life').value = parseInt(document.getElementById('base-life').value)+increaseWith;">add</button>

Auto Calculate with already given value

I want to get fee value with already calculated value without using onblur function.
HTML and JS Snippet:
var initialcost = document.getElementById("initialcost");
var Tfee = initialcost - (initialcost * 5)/100;
document.getElementById("fee").value = +Tfee;
<input type="text" readonly="readonly" value="1000" id="initialcost">
<input type="text" readonly="readonly" id="fee">
After autocalculating read-only value from id="initialcost" display the value in id="fee"
After trying this I get no result
Kindly help
You're attempting to calculate things using the element, not its value.
Replace
var initialcost = document.getElementById("initialcost");
with
var initialcost = parseFloat(document.getElementById("initialcost").value);
Example with automatic recalculation to boot:
var initialCostElement = document.getElementById("initialcost");
function compute() {
var initialcost = parseFloat(initialCostElement.value);
var Tfee = initialcost - (initialcost * 5)/100;
document.getElementById("fee").value = +Tfee;
}
initialCostElement.addEventListener("input", compute, false);
compute();
<input type="number" value="1000" id="initialcost">
<input type="text" readonly="readonly" id="fee">
first of all,
you are using the html element itself instead of its value in your calculation.
use:
var initialcost = document.getElementById("initialcost").value;
Moreover, I would replace the "var" type with contest in both variables since this are constants with non-changing values. The var is a more "old-fashioned" approach since "let" and "const" are newer additions to the js syntax,
Good luck!

Updating form input field value based on other inputs

I am trying to build a calculator of sorts where you an input all but one variable and get the final variable autofilled in the form. I am trying this using a javascript function oninput for the form. However I am not sure how to achieve this. I have written a basic example of what I want below (though this does not work):
<form oninput="thermal()">
<input type="number" name="avgTemp" id="avgTemp" class="five-col">
<input type="number" name="volume" id="volume" class="five-col">
<input type="number" name="deltaTemp" id="deltaTemp" class="five-col">
<input type="number" name="Q" id="Q" class="five-col">
</form>
function thermal(){
var volume = document.getElementById("volume");
var deltaTemp= document.getElementById("deltaTemp");
value = deltaTemp;
}
function thermal(){
let avgTemp = document.getElementById("avgTemp").value;
let volume = document.getElementById("volume").value;
let deltaTemp = document.getElementById("deltaTemp").value;
let q = document.getElementById("Q") // no value here yet; we will make this our total
console.log(avgTemp, volume, deltaTemp, q)
}
Well, let's start with this. This gives you each input value individually - from here, we can implement the pertinent logic to combine input values into one input field. I will make the Q input our "total" just so you can get a picture of how combining may look.
function thermal(){
let avgTemp = document.getElementById("avgTemp").value;
let volume = document.getElementById("volume").value;
let deltaTemp = document.getElementById("deltaTemp").value;
let q = document.getElementById("Q");
let total = Number(avgTemp) + Number(volume) + Number(deltaTemp)
console.log(total)
q.value = total
}
I am not sure what you are looking for but this should give you a decent head start. Fire away if you have any questions.
If you want to play around with it, here is the codepen:
https://codepen.io/Pulse3358/pen/ExPZaVM

How to copy and output text from another textbox with Javascript?

<input type="hidden" id="prevTicketNo" value="6"/>
<script>
var ticketNo = document.getElementById(prevTicketNo).value +1;
document.getElementById('currentTicketNo').value = ticketNo;
</script>
<input id="currentTicketNo" value=""/>
What I am trying to do:
The prevTicketNo is a value captured from somewhere else. I need that to load as a hidden field so I used type="hidden". Once the value in this textbox is loaded, I need to +1 so that the number increases for my current ticket.
Is the right approach?
You must change the value of the first input to integer.
var ticketNo =parseInt((document.getElementById('prevTicketNo').value),10)+1;
document.getElementById('currentTicketNo').value = ticketNo;
JSBin
Javascript:
var hiddenVal = document.getElementById("prevTicketNo");
var newTicketNo = Number(hiddenVal.value) + 1;
alert(newTicketNo);
HTML:
<input type="hidden" id="prevTicketNo" value="6"/>
If you can get the previous ticket number and output it into a hidden field (obviously via some kind of server side script), why can't you just output it directly into your text input?
eg. In PHP write this:
<input id="currentTicketNo" value="<?php echo $prevTicketNo + 1; ?>" />

How do I execute a JavaScript function from clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
<script language="Javascript">
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex)
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex)
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex)
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex)
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex)
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}};
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="var currency = KWD">
<input type="button" value="USD" OnClick="var currency = USD">
<input type="button" value="GBP" OnClick="var currency = GBP">
<input type="button" value="EUR" OnClick="var currency = EUR">
<input type="button" value="CAD" OnClick="var currency = CAD">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="showMeArea.value=finddivid(mktprc,trdval);">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="30">
</html>
If you run this html in your browser you should see what I am trying to achieve.
It is far from complete but here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started 4 days ago!) so would like any like of help that can be offered.
Thanks in advance of your comments.
The first request requires that you put the currency into the actual script, and I would recommend using a setter function:
<script language="Javascript">
var currency; // you might want to set this at a default just in case
function setCurrency(val) { currency = val; } // Setter function
function finddivid(marketprice,tradevalue) {
Then call it in your button click:
<input type="button" value="KWD" onClick="setCurrency('KWD');">
As for the second request, I'd say you have the concept down well enough, but you don't have the method exactly right. First your inputs will need an id attribute:
<input name="mktprc" id="mktprc" input type="number">
<input name="trdval" id="trdval" input type="number">
The name attribute is used for posting values, the id attribute is used by javascript to find elements within a page. Using jQuery would make retrieving these elements easy, but I'll show both the jQuery and the standard JavaScript method of doing this:
jQuery:
<input type="button" value="Calculate" OnClick="$('#showMeArea').val(finddivid($('#mktprc'),$(#'trdval')));">
The $('#id') selects an element. The method .val() sets the value.
Note for the jQuery purists: Yes, there are much better/sophisticated ways to accomplish this with jQuery, but this answer is targeted to my perception of OP's JavaScript capability.
Standard Javascript:
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value = finddivid(document.getElementById('mktprc'),document.getElementById('trdval'));">

Categories

Resources