update multiple variables with onchange event in vanilla javascript - javascript

I have a series of functions that take in several inputs and generate several outputs. When any input changes all the outputs should change as well. The javascript is as follows:
function calcOne(a,b,c){
return a+b+c
}
function calcTwo(c,d){
return c*d
}
function calcThreee(d,e){
return d+e
}
var a = parseFloat(document.getElementByID('a').value);
var b = parseFloat(document.getElementByID('b').value);
var c = parseFloat(document.getElementByID('c').value);
var d = parseFloat(calcOne(a,b,c));
var e = parseFloat(calcTwo(c,d));
var f = parseFloat(calcThree(d,e));
document.getElementbyId("result_d").innerHTML = d;
document.getElementbyId("result_e").innerHTML = e;
document.getElementbyId("result_f").innerHTML = f;
So, when any of inputs a, b, or c change, then results in d, e, and f will change.
The corresponding html is:
<html>
<body>
<form id="myForm">
<input id='a' value="1"><br>
<input id='b' value="2"><br>
<input id='c' value="3"><br>
</form>
<p id="result_d"></p>
<p id="result_e"></p>
<p id="result_f"></p>
<script src="myScript.js"></script>
</body>
</html>
How do I add an event listener such that any change to the form inputs a,b,c causes the displayed results d, e, and f to be updated? Note, that in my actual code (not the example above) there are about 50 variables and 50 functions, but all are very computationally lite (not much more than shown above) if that matters.

Add an event listener to the form to detect the input was altered.
var form = document.getElementById("myForm");
form.addEventListener("input", function (evt) {
console.log("changed!", evt.target.id);
// call a function that does the calculations
});
<form id="myForm">
<input id='a' value="1"><br>
<input id='b' value="2"><br>
<input id='c' value="3"><br>
</form>

Wrap all your calculations in a function (recalc below) and call it once when the page loads, but also call it from an event listener for all the input elements
note also, that you don;t need to call parseFloat on the results of your functions - theyre already numeric.
function calcOne(a,b,c){
return a+b+c
}
function calcTwo(c,d){
return c*d
}
function calcThree(d,e){
return d+e
}
document.querySelectorAll("input").forEach(x => x.addEventListener("change",recalc));
function recalc(){
var a = parseFloat(document.getElementById('a').value);
var b = parseFloat(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = calcOne(a,b,c);
var e = calcTwo(c,d);
var f = calcThree(d,e);
document.getElementById("result_d").innerHTML = d;
document.getElementById("result_e").innerHTML = e;
document.getElementById("result_f").innerHTML = f;
}
recalc()
<form id="myForm">
<input id='a' value="1"><br>
<input id='b' value="2"><br>
<input id='c' value="3"><br>
</form>
<p id="result_d"></p>
<p id="result_e"></p>
<p id="result_f"></p>

you can use an index since you have as many input as result para, with a input & result class:
let inputs = document.getElementsByClassName('input');
let results = document.getElementByClassName('result');
for(let i = 0; i < inputs.length; i++){
input[i].addEventListener('keydown', () => {
result[i] = do_some_suff;
});
}

Related

calculating from an input

I'm starting studying the DOM in javascript and I'd like to create a program which makes the sum of two numbers given on input and show it.
I'd like to know what functions should I use, and what functions it is better I didn't.
This is my (very simple) html code:
let warp = document.getElementById('warp');
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
let res = document.getElementById('res');
//res.addEventListener('click', calcul);
//res.onclick(calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul(first, second) {
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
let answerElemenet = document.createElement("h1");
// You can create a h1 element to display your answer after calculating it
document.body.appendChild(answerElemenet);
// Inside the calculate Function you get the values of input one and two
// and then you store the sum value in a variable and just change your
// answerElement to have the innerHTML value of the finalSum Variable
function calculate(){
let valueOne = parseFloat(document.getElementById('first').value);
let valueTwo = parseFloat(document.getElementById('second').value);
let finalSum = valueOne + valueTwo;
answerElemenet.innerHTML = finalSum;
}
Welcome to Stackoverflow!
I copied your answer and made some small changes. Here comes a brief description and explanation of what you could do better:
If you don't plan to change these references use const instead of let. Also try to keep input elements separated from their values. The reference to the input probably won't change but their value most certainly will.
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
When calculating input values, you usually want them as fresh as possible so instead of saving input values right at the beginning of the script, you get them when you need them, in the calcul() function.
You will also need some kind of validation. Here we try to convert the input to a number and set to zero if not possible:
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
The preferred way of adding event handlers to DOM elements is using the event API. So to call the calcul()function you use the line you had commented:
res.addEventListener('click', calcul);
This also means you should remove the onClick attribute from the DOM. Also, input cannot have children:
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
All together looks like this:
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
res.addEventListener('click', calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
</form>
<div>
</body>
Keep up the good job and never stop asking questions!
This will work. You just need to call the values based on their id in the calcul() function itself.
let warp = document.getElementById('warp');
let res = document.getElementById('res');
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul() {
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
if(isNaN(one) || isNaN(two)){
event.preventDefault();
return
}
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>

Issues outputting text via JavaScript

https://codepen.io/kev_daddy/pen/MMWEMG
I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.
The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.
The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.
I am sure that I am missing something, but how do I ensure that the sum is outputted?
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult; }
var input = document.getElementById("result");
var output = document.getElementById("output"); input.addEventListener("input", function() {
output.innerText = this.value;
});
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
updateText(myResult)
}
function updateText(val) {
document.getElementById("output").innerText = val;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!

Javascript can't get values from input

I'm trying to get the values from the inputs in my form with JavaScript. But whenever I hit submit, I either get nothing, 0 or undefined. Mostly undefined. It doesn't seem to get any of the values.
Here's the code
<form id="ecoCalculator">
<div class="form-group">
<label for="k0">Start Kapital</label>
<input type="number" name="k0" class="form-control" id="k0">
</div>
<div class="form-group">
<label for="kn">Slut Kapital</label>
<input type="number" name="kn" class="form-control" id="kn">
</div>
<div class="form-group">
<label for="x">Rente</label>
<input type="number" name="x" class="form-control" id="x">
</div>
<div class="form-group">
<label for="n">Terminer</label>
<input type="number" name="n" class="form-control" id="n">
</div>
<div class="ecoButtons">
<input type="button" value="Udregn" class="btn btn-default" onclick="k0Eco()">
<input type="reset" value="Ryd" class="btn btn-default">
</div>
</form>
<div class="ecoResult">
<p id="ecoResult">Resultat</p>
</div>
</div>
<script type="text/javascript">
// Public Variables
var k0 = document.getElementById('k0').value();
var kn = document.getElementById('kn').value();
var x = document.getElementById('x').value();
var n = document.getElementById('n').value();
// Calculation of Initial Capital
function k0Eco() {
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0;
}
I've looked around at different questions but haven't found a solution to this yet.
I've tried to change the names of the inputs, having the function only display a single value, but still no result.
Thanks
value isn't a function, it's a property. Change
var k0 = document.getElementById('k0').value()
to
var k0 = document.getElementById('k0').value
Your script also runs on page load, so nothing is filled yet. You need to put the whole thing in a submit handler:
document.getElementById('ecoCalculator').addEventListener('submit', function(e) {
e.preventDefault();
// your code here
});
Now remove the inline js from the button and make it type submit:
<input type="submit" value="Udregn" class="btn btn-default" />
And remove the function in your js
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0Value;
Here's a working fiddle
you need to parse the input value in int. for eg.
// Public Variables
var k0 = parseInt(document.getElementById('k0').value);
var kn = parseInt(document.getElementById('kn').value);
var x = parseIntdocument.getElementById('x').value);
var n = parseIntdocument.getElementById('n').value);
Use value instead of value(). It is a property not a function.
Put your variables inside your function. When page loads you variables
are getting the value of the inputs and there is nothing there.
function k0Eco() {
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
var k0Value = kn / (1 + x) ^ n;
document.getElementById("ecoResult").innerHTML = k0Value;
}
Put you javascript code inside <head> tag or at least before the button. When you try to fire onclick() event, your function is not created yet.

Can't invoke a function with js

Here is my html and js:
function calculateFun()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var c = document.getElementById('c').value;
var d = document.getElementById('d').value;
var e = document.getElementById('e').value;
var f = a*b;
document.getElementById('f').value = f;
var g = (f + (f*(d/100))).toFixed();
document.getElementById('g').value = g;
var h = ((1 -((a*c)/e))*100).toFixed();
document.getElementById('h').value = h;
}
<input type="number" id="a" onkeyup="calculateFun();" />
<input type="number" id="b" onkeyup="calculateFun();" />
<input type="number" id="c" value="100" />
<input type="number" id="d" value="50" />
<input type="number" id="e" onkeyup="calculateFun();" />
<br><br><p>******</p><br><br>
<input type="number" id="f" />
<input type="number" id="g" />
<input type="number" id="h" />
I tried this code in JSFIDDLE:
https://jsfiddle.net/1ex3b1sa/
but it is not working. also in my site, the function isn't invoked.
it is strange because, i can invoke other functions that i did, almost with the same way.
i tried changing to onclick, onkeypress or onkeydown, but can't see any results..
any ideas? maybe i have a typo? or maybe its a chrome problem?
In JSFiddle, you need to set your JavaScript wrap to "No wrap - in <head>" or else you'll get an "Uncaught ReferenceError: calculateFun is not defined" error.
Make sure that the function is here:
<html>
<head>
<script type="text/javascript">
function calculateFun() {
// ...
You could actually keep the function definition in the onLoad wrap and change:
function calculateFun() {
To this:
window.calculateFun = function() {
And it will work because you are adding your function as a static method to the browser's Window.
On the left side of jsfiddle.net is a box with "Frameworks & Extensions".
In the second select box you have to select:
No wrap - in <body>
or
No wrap - in <head>
Then it will work. If you dont do that the function will not be defind and it will run just once (in the OnLoad Event).
please learn jquery, its not that hard and will help you!
your fiddle in functioning jquery: https://jsfiddle.net/1ex3b1sa/3/
input-fields got class='calc'
and js:
$('.calc').keyup(function(){
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var d = $('#d').val();
var e = $('#e').val();
var f = a * b;
$('#f').val(f);
var g = (f + (f*(d/100))).toFixed();
$('#g').val(g);
var h = ((1 -((a*c)/e))*100).toFixed();
$('#h').val(h);
});

how to use id of a button in if statement using javascript

I am a beginner to Javascript and am trying to perform arithmetic functions.
Here is my code below:
script
<script language="javascript" type="text/javascript">
function func(a,b)
{
var a = document.getElementById("a");
var b = document.getElementById("b");
if (document.getElementById("btnadd").Text == 'Add')
{
var c = a + b;
document.getElementById("rslt").innerHTML =c;
}
}
</script>
aspx
<asp:Button ID="btnadd" Text="Add" runat="server" OnClientClick="func(txtn1,txtn2)" />
<p id="rslt"></p>
My idea is, when I click say 'add' button the value of two textbox should be passed to the script and are assigned to two variables.
With those two variables all arithmetic (add,sub,div,mul) should be done.
What you could do is also pass the button that was clicked, using this. That way you know the text of the button that was clicked. And since you are using a server side button, be sure to include return false; from your JavaScript call to prevent it from posting back and clearing your <p> tag.
<asp:Button ID="btnadd" runat="server" Text="Add"
OnClientClick="func('txtn1', 'txtn2', this); return false;" />
function func(a, b, btn) {
var txtn1 = document.getElementById(a);
var txtn2 = document.getElementById(b);
var rslt = document.getElementById('rslt');
if(btn.value == 'Add')
rslt.innerHTML = parseInt(txtn1.value) + parseInt(txtn2.value);
}
According to here:
You have to use anonymous functions/handlers to react on such user-interactions without reloading the page. Also look at jquery (http://api.jquery.com/click/) which gives you a simpler api to write those things.
<script language="javascript" type="text/javascript">
function func(a,b) {
var a = document.getElementById("a");
var b = document.getElementById("b");
var btn = document.getElementsById("btnadd");
btn.onclick = function() {
var c = a + b;
// alert("Result = " + c );
document.getElementById("rslt").innerHTML =c;
}
}
</script>
Hope that your requirement is to perform arithmetic operations with two numbers from the text boxes.For that you need not pass text boxes as parameters to the script since it uses document.getElementById. directly access the textbox inside the script as follows:
<head><script>
function myFunction(a) {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x;
if(a==1)
x = +y + +z;
else if(a==2)
x=+y - +z;
else
x=0;
document.getElementById("demo").innerHTML = x;
}
</script></head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<button onclick="myFunction(1)">Addition</button>
<button onclick="myFunction(2)">Subtraction</button>
<p id="demo"></p>
</body>
The above code will perform addition and subtraction based on button click
function func(a,b) {
var a,b;
a=$("#a").val();
b=$("#b").val();
if ($("#btnAdd").val() == 'Add') {
$("#a").val(+(a) + +(b));
}
}
And Set button value to Add
Or if you want to reduce your code then use this code
if ($("#btnAdd").val() == 'Add') {
$("#a").val( +($("#a").val()) + +($("#b").val() ));
}

Categories