Can't invoke a function with js - javascript

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);
});

Related

update multiple variables with onchange event in vanilla 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;
});
}

How to use DOM referenced .value's in different scopes? (refactoring/scope issue)

Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>
<html>
<body>
See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button><br>
<p>Thank HumbleOldMan later, go get rich now.</p>
var profit = function(){
var bp = document.getElementById("bp").value;
var n = document.getElementById("n").value;
var sp = document.getElementById("sp").value;
var t = document.getElementById("t").value;
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(result);
document.getElementById("r").value = result;
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//
And here is what I tried doing
<script type="text/javascript">
var bp = Number(document.getElementById("bp").value);
var n = Number(document.getElementById("n").value);
var sp = Number(document.getElementById("sp").value);
var t = Number(document.getElementById("t").value);
var r = Number(document.getElementById("r").value);
var result;
var calcProfit = function(bp,n,sp,t,r){
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(Number(result));
r = Number(result);
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
</script>
The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.
You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.

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.

script not producing result

New to javascript. Would very much like to produce a simple calculator that uses three inputs and 4 fixed values to produce and report a 'peak power output' value. Code is as follows:
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
html:
<td>
<input id="vj" type="text" oninput="calculate()" />
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" />
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" />
</td>
have this in a html page with table to display input and results, input works, but not results.
You have jquery tagged, so here is a jQuery version.
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = $('#vj').val();
hgt = $('#hgt').val();
wgt = $('#wgt').val();
result = $('#peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.val(peakresult);
}
$(document).ready(function() {
$('input[type="text"]').on('blur', function() {
calculate();
});
});
</script>
This assumes you also have <input type="text" id="peakresult" /> in your HTML.
I added a jQuery event handler that will call the calculate button when the user leaves the input field. That could be more useful than having a handler in the field tag.
if you replace
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
by
vj = Number(document.getElementById('vjump').value);
hgt = Number(document.getElementById('height').value);
wgt = Number(document.getElementById('weight').value);
It should work.
BUT WITH NO check for correct input.
(EDITED)
This following code is working (Tested on Chrome)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = Number(document.getElementById('vj').value);
hgt = Number(document.getElementById('hgt').value);
wgt = Number(document.getElementById('wgt').value);
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
</head>
<body>
<td>
<input id="vj" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="peakresult" type="text" value="0"/>
</td>
</body>
You can use unary plus, +, to turn your values into a number and then perform operations on them:
function add() {
var a = +document.getElementById('firstOperand').value;
var b = +document.getElementById('secondOperand').value;
return a + b;
}
Also your html suggests you are invoking the calculate function every keystroke by using oninput. You can use onblur to call the calculate function after the user leaves the field.
You might need parse text into integer
parseInt(val);
Check this live sample
http://jsfiddle.net/VdrWL/2/
Hope it helps.

Change value of form boxes with jQuery onBlur

I'm looking to write a jQuery function that will change the value of other input boxes when an onBlur event occurs. In the code below, I'm attempting to read in the value of the input box that has been altered and use its value to manipulate the value of the other input boxes. Eventually, this will be used as a conversion utility. I feel like I'm pretty close here, can someone help?
Thanks!
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js">
<script type="text/javascript">
$('#a').bind('blur', function() {
var a = $('#a').val();
var b = a*1;
var c = a*1;
$('#b').val(b);
$('#c').val(c);
});
$('#b').bind('blur', function() {
var b = $('#b').val();
var a = b*2;
var c = b*2;
$('#a').val(b);
$('#c').val(c);
});
$('#c').bind('blur', function() {
var c = $('#c').val();
var a = c*3;
var b = c*3;
$('#a').val(a);
$('#b').val(b);
});
</script>
<div style="width:500px">
<table width="500">
<tr>
<td><input type="text" id="a" value="1"/></td>
<td><input type="text" id="b" value="1"/></td>
<td><input type="text" id="c" value="1"/></td>
</tr>
</table>
</div>
Change
$('#a').val(b);
to
$('#a').val(a);
in second bind.
i found your error:
change this:
$('#b').bind('blur', function() {
var b = $('#b').val();
var a = b*2;
var c = b*2;
$('#a').val(b);
$('#c').val(c);
});
to this:
$('#b').bind('blur', function() {
var b = $('#b').val();
var a = b*2;
var c = b*2;
$('#a').val(a);
$('#c').val(c);
});
you accidentally gave $('#a').val = b when there is no b
see answer working fully here:
http://jsfiddle.net/Ru6FV/
You would probably want to fire whole javascript after html is loaded correctly:
$(function() {
$('#a').bind(...
...
});
});
What exactly is the issue? It seems to work somehow (didn't check for the calculations)... implementation with jsfiddle
You are missing the </script> tag after loading jquery.

Categories