The script below calculates a simple sum, displaying an error if the sum exceeds or falls below 100. Despite the error message, the user can still proceed to the next page. I want to restrict the user from moving to the next page until the sum equals 100.
<table class="table-bordered" style=" width: 80%; margin-left: 10%;" >
<tr style="background-color:#ffb380">
<td scope="col" colspan="1" style="text-align:center"> Quante Palline per la Scelta 1 </td>
<td scope="col" colspan="1" style="text-align:center"> Quanti Palline per la Scelta 2 </td>
<td scope="col" colspan="1" style="text-align:center"> Totale Palline Assegnate </td>
</tr>
<tr style="background-color:#ffe0cc">
<td> <input class="pref_input" id="pref1" type="number" name="pref1" min="0" max="100" style="width: 50%; margin-left: 25%"> </td>
<td> <input class="pref_input" id="pref2" type="number" name="pref2" min="0" max="100" style="width: 50%; margin-left: 25%"> </td>
<td> <span id="sum_token" style="width: 50%; margin-left: 37%" ></span> su 100</td>
</tr>
</table>
<div id="error" class="hide"><b>La somma dei gettoni deve essere 100</b></div>
<script>window.onload = init_sum_token();
function init_sum_token() {
sum_token = document.getElementById("sum_token");
pref1 = document.getElementById("pref1");
pref2 = document.getElementById("pref2");
document.querySelectorAll(".pref_input").forEach((item) => {
item.addEventListener("change", (event) => {
sum_prefs =
get_input_value(pref1) +
get_input_value(pref2);
let sum = parseFloat(sum_prefs);
if (sum != 100) {
sum = sum_prefs;
document.getElementById("error").className = "show";
} else {
document.getElementById("error").className = "hide";
}
sum_token.innerHTML = sum;
});
});
}
function get_input_value(input) {
if (input.value == "") {
return 0;
} else {
return parseFloat(input.value);
}
if (input.value != 100) {
return "error";
}
}
</script>