HakoStan
HakoStan

Reputation: 69

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?

Upvotes: 1

Views: 325

Answers (3)

Michael Unterthurner
Michael Unterthurner

Reputation: 941

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).

Upvotes: 1

roeb
roeb

Reputation: 487

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

});

Upvotes: -2

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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.

enter image description here

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.

Upvotes: 4

Related Questions