Search code examples
javascriptfunctiononclickjsfiddle

js function not returning onclick


I've created a function that I can't get to return with onclick.

I'm sure it's something v simple i'm missing.

HTML:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="schedule.js"></script>
</head>
<body>

     <input type="button" onclick="computeSchedule();" value="Submit" /><br>
     <p id="scheduleOutput"></p>

</body>
</html>

JS:

function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;

for (var i=0; i<=number_of_payments; i++) {
    var interest = remaining * (interest_rate/100/payments_per_year);
    var principle = (payment-interest);
    var row = [i, principle>0?principle:0, interest>0?interest:0, remaining>0?remaining:0];
    schedule.push(row);
    remaining -= principle
}

return schedule;
}

var list = JSON.stringify(computeSchedule(100000, 0.005, 12, 15, 843.86), 0, 4)

document.getElementById('scheduleOutput').innerHTML = list;

I can get the function to automatically return in jsFiddle onload, but when I change js settings to "no wrap - in head"it doesn't work. I assume whatever is happening there is also happening when I try to run outside of jsFiddle?


Solution

  • You sripts runs before body content is ready. That is why document.getElementById seems not to be working, because such element does not exist at this point of time.

    Try to wrap your code in simple "content load" listener to be sure that it will be run after all elements are ready:

    document.addEventListener('DOMContentLoaded', function() {
        function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
            var schedule = [];
            var remaining = loan_amount;
            var number_of_payments = payments_per_year * years;
    
            for (var i=0; i<=number_of_payments; i++) {
                var interest = remaining * (interest_rate/100/payments_per_year);
                var principle = (payment-interest);
                var row = [i, principle>0?principle:0, interest>0?interest:0, remaining>0?remaining:0];
                schedule.push(row);
                remaining -= principle
            }
    
            return schedule;
        }
    
        var list = JSON.stringify(computeSchedule(100000, 0.005, 12, 15, 843.86), 0, 4)
    
        document.getElementById('scheduleOutput').innerHTML = list;
    });
    

    And yes, your onclick is now passing no data to the function. So, you also need to pass params to it and everything should work fine.