my knowledge in Javascript is basic. I'm trying to run a function when clicking the button submit, but when I do the page shows for a fraction of a second the result in the webpage but then it refreshes automatically showing the page in blank again. Any idea on how to fix this? Thanks in advance.
HTML
<section class="container-form">
<div>
<p>
Por favor ingresar los datos de tu préstamo para hacer el cálculo.
</p>
</div>
<form action="" id="form">
<input type="number" name="capital" id="capital" placeholder="Capital Inicial $">
<input type="number" name="rate" id="rate" placeholder="Tasa de Interés Anual %">
<input type="number" name="periods" id="periods" placeholder="Cantidad de cuotas">
<div>
<label for="frequency">Frecuencia de las cuotas</label>
<select name="frequency" id="frequency">
<option value="monthly">Mensual</option>
</select>
</div>
<div class="container-btn">
<input type="submit" id="btnSubmit" class="submit" onclick="calculateAnnuity()">
</div>
</form>
</section>
<section class="container-table">
<table id="table-results" class="table">
<thead>
<tr>
<th>Nº</th>
<th>Cuota</th>
<th>Interés</th>
<th>Capital</th>
<th>Saldo</th>
</tr>
</thead>
<tbody></tbody>
</table>
</section>
JS
// Declarar variables
let capital;
let rate;
let frequency;
let periods;
let btnSubmit;
let tableResults;
// Asignar valores a variables desde el form
capital = document.getElementById('capital');
rate = document.getElementById('rate');
frequency = document.getElementById('frequency');
periods = document.getElementById('periods');
btnSubmit = document.getElementById('btnSubmit');
tableResults = document.querySelector('#table-results tbody')
// Disparador de funcións
/* btnSubmit.addEventListener('click',() => {
calculateAnnuity(capital.value, rate.value, frequency.value, periods.value)
}) */
function calculateAnnuity (capital, rate, frequency, periods) {
// Declarar variables
let annuity = 0;
let actualCapital = capital;
let interestFee = 0;
let capitalFee = 0;
// Calculo de cuota
annuity = capital * (rate/100/12)
/
(1-Math.pow(1+rate/100/12,-periods));
console.log(typeof(capital)+" "+typeof(rate)+" "+typeof(periods)+" "+typeof(annuity))
for(let i = 0; i <= periods; i++) {
const row = document.createElement('tr');
row.innerHTML = `
<td>${i}</td>
<td>${parseFloat(annuity).toFixed(2)}</td>
<td>${parseFloat(interestFee).toFixed(2)}</td>
<td>${parseFloat(capitalFee).toFixed(2)}</td>
<td>${parseFloat(actualCapital).toFixed(2)}</td>
`
switch (frequency) {
case 'monthly':
interestFee = actualCapital * rate/100/12;
default:
continue;
}
capitalFee = annuity - interestFee;
actualCapital = actualCapital - capitalFee;
console.log(actualCapital);
tableResults.appendChild(row)
}
}