简体   繁体   中英

Javascript runs function only once

The

HTML

<p>What factorial would you want to calculate?</p>
<input id="factorium" type="number">
<input id="submission" type="submit" value="Calculate">

Javascript

function factorial(x) {
    if (x === 0) {
        return 1;
    }
    return x * factorial(x - 1);
}

    var inputBox = document.getElementById('factorium').value;
    var submission = document.getElementById('submission');
    submission.onclick = function(){console.log(factorial(inputBox))};

Edited -

The submit button only works once, I need to refresh the page for it to work again, any idea how to fix this?

Your JavaScript code can be reduced to one line:

document.getElementById('factorium').value();

This is enough to trigger the error. The problem is .value() , which should be .value instead. As the error message says, .value is not a function and can't be called.

I created a new function that only executes the above code as follows:

function getVals(){

    var inputBox = document.getElementById('factorium').value;
    var submission = document.getElementById('submission');
    console.log(factorial(inputBox));
}

and on the input submit button I've added:

<input id="submission" type="submit" value="Calculate" onclick="getVals()">

JS Fiddle Link

<p>What factorial would you want to calculate?</p>
<input id="factorium" type="number">
<input id="submission" type="submit" value="Calculate" onclick="calcFactorial()">

<script>

    function factorial(x) {
        if (x === 0) {
            return 1;
        }
        return x * factorial(x - 1);
    }

        function calcFactorial(){
            var inputBox = document.getElementById('factorium').value;
            var submission = document.getElementById('submission');
            console.log(factorial(inputBox));
        }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM