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

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *