Search code examples
javascripthtmlonkeyup

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?


Solution

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