@glasstream2000 it seem like string concatenation work on two values. Try to type cast value to int with parseInt().
function calculate(selected) {
return selected.reduce((a, b) => parseInt(a) + parseInt(b)) / selected.length;
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
New to javascript so any help would be appreciated! I have a table in a foreach that pulls from the DB and puts that info into a table. I have two sets of checkboxes that I can check and want it to display the averages of what is checked in an alert window.
Table:
<table class="table mt-4 table table-striped" id="suppTable">
<thead>
<th scope="col">Avg Entry</th>
<th scope="col">Avg Highest</th>
<th scope="col">Entry</th>
<th scope="col">Highest</th>
</thead>
<tbody>
@foreach($supp as $supp)
<tr>
<td><input type="checkbox" id="entry" value="{{ $supp->entry}}" name="rows[]"></td>
<td><input type="checkbox" id="highest" value="{{$supp->highest}}" name="rows[]"></td>
<td><span style="color: gray">{{$supp->system->name}}</span></td>
<td><span style="color: #007E33">{{$supp->entry}} </span></td>
<td><span style="color: #007E33">{{$supp->highest}} </span></td>
<td><span style="color: #007E33">{{$supp->days}} </span></td>
<td><span style="color: gray">{{$supp->employed }}</span></td>
</tr>
@endforeach
</tbody>
</table>
<input type = "button" value = "Get" onclick = "GetSelected()" />
and my javascript:
<script type="text/javascript">
function calculate(selected) {
return selected.reduce((a, b) => a + b) / selected.length;
}
function GetSelected() {
//Create an Array.
var selected = new Array();
//Reference the Table.
var suppTable = document.getElementById("suppTable");
//Reference all the CheckBoxes in Table.
var entry = suppTable.getElementsByTagName("INPUT");
// Loop and push the checked CheckBox value in Array.
for (var i = 0; i < entry.length; i++) {
if (entry[i].checked) {
selected.push(entry[i].value);
}
}
alert("Average: " + calculate(selected));
}
</script>
It pops up the alert with the values checked, but it shows the values like: 10002000 (if 1000 was checked and another checked value was 2000) when it is suppose to be averaging 1000 and 2000 and only show 1500 (which is the average of 3000 when they are added and then divided by how many are checked. Any ideas or point in the right direction?
Please or to participate in this conversation.