Which value does the function hand over?
None, Your function is not returning any value so there is no handing over anything. If you, however, want to return any value you can do so by the return statement.
ie:
function checkTotal() {
var sum = 0;
document.listForm.total.value = '';
for (i = 0; i < document.listForm.choice.length; i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
return sum;
}
So when you call the function you can save its return value
Like :
var total = checkTotal();
How is it called?
Currently its being called using event listener attribute. ie. onChange
its like doing this in javascript
document.querySelectorAll('input[type="checkbox"]')
.forEach(function(){
this.addEventListener("change", checkTotal)
})
How can I make sum a global variable without destroying the function?
You just have to declare the var sum = 0; outside the function in a global scope like this
var sum = 0;
function checkTotal() {
sum = 0;
document.listForm.total.value = '';
for (i = 0; i < document.listForm.choice.length; i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
any function in javascript inherit the scope from its parents too so anything available before the function is declared, is also available inside the function (unlike php).
A note though: variables declared using let and const are block scoped. Meaning: they can’t be accessed from outside their immediate enclosing {...}
Putting everything together and correcting some errors
The final code looks like this.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="list-form">
<table>
<tr>
<td>A</td>
<td>Inhalt 1</td>
<td><input type="checkbox" name="Inhalt_1" value="1"></td>
</tr>
<tr>
<td>B</td>
<td>Inhalt 2</td>
<td><input type="checkbox" name="Inhalt_2" value="1"></td>
</tr>
<tr>
<td>Total:</td>
<td colspan="2"><input disabled type="text" id="total" name="total" value="0" /></td>
</tr>
</table>
</form>
<script src="path/to/your/js/file.js" type="text/javascript"></script>
</body>
</html>
JS
var checkboxes = document.forms[0].querySelectorAll('input[type="checkbox"]'),
inpTotal = document.getElementById('total'),
sum = 0;
// first we define the checkTotal
function checkTotal() {
sum = 0;
checkboxes.forEach(el => {
if (el.checked) sum += +el.value;
});
inpTotal.value = sum;
// alert(sum);
}
// then we add the event listeners
checkboxes.forEach(el => el.addEventListener("change", checkTotal));
PS: It is a good practice to put all your javascript in a seperate file from the html where possible.