Вы можете найти все выбранные флажки и использовать полученную длину для деления на общую сумму пожертвований во всех организациях.
const form = document.forms[0];
form.elements['calc-btn'].addEventListener('click', function() {
let total = parseInt(form.elements['amount'].value, 10);
let count = selectedCheckboxes(form, 'organisation').length;
document.getElementById('result').textContent = average(total, count).toFixed(2);
});
triggerEvent(form.elements['calc-btn'], 'click'); // Calculate on load
function average(total, count) {
return count > 0 ? total / count : 0;
}
function selectedCheckboxes(form, name) {
return Array.from(form.elements[name]).filter(c => c.checked);
}
function triggerEvent(el, eventName) {
var event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, false);
el.dispatchEvent(event);
}
fieldset {
margin-bottom: 0.5em;
}
.result-display {
margin-top: 1em;
}
<form action="/action_page.php" method="get">
<h2>Donation Form</h2>
<fieldset>
<legend>Organizations</legend>
<input type="checkbox" name="organisation" value="WHO" checked>
Vælg velgørenhedsorgsnisation WHO<br>
<input type="checkbox" name="organisation" value="Plastic Change" checked>
Vælg velgørenhedsorgsnisation Plastic Change<br>
<input type="checkbox" name="organisation" value="Sea Turtle Conservancy" checked>
Vælg velgørenhedsorgsnisation Sea Turtle Conservancy<br>
</fieldset>
<fieldset>
<legend>Donation amount (€)</legend>
<input type="text" name="amount" value="10.00" />
</fieldset>
<input type="button" id="calc-btn" value="Calculate" />
<div class="result-display">Calculated donation amount: <span id="result">0</span>€</div>
</form>