Im trying to code an online scorecard for our mini golf but I cant seem to figure out how to make this work without copying the same function twice. I would like to be able to make it work for 2-4 players. Here is my code:
<table>
<thead>
<tr>
<th>Trou</th>
<th>Par</th>
<th><input type="text" value="#1"></th>
<th><input type="text" value="#2"></th>
</tr>
</thead>
<tbody>
<? for($i=1;$i<19;$i ){ ?>
<tr >
<td><? echo $i; ?></td>
<td>2</td>
<td><input onblur="findTotal()" type="number" name="qty" id="qty"/></td>
<td><input onblur="findTotal2()" type="number" name="qty2" id="qty2"/></td>
</tr>
<? } ?>
<tr >
<td>Total</td>
<td>52</td>
<td><input type="text" name="total" id="total"/></td>
<td><input type="text" name="total2" id="total2"/></td>
</tr>
</tbody>
</table>
function findTotal(){
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i ){
if(parseInt(arr[i].value))
tot = parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
function findTotal2(){
var arr = document.getElementsByName('qty2');
var tot=0;
for(var i=0;i<arr.length;i ){
if(parseInt(arr[i].value))
tot = parseInt(arr[i].value);
}
document.getElementById('total2').value = tot;
}
I am trying to make this function work for 1-4 players without copying the same function more than once
CodePudding user response:
You could add arguments to the function like so:
function findTotal(qty_element_name, total_element_name){
var arr = document.getElementsByName(qty_element_name);
var tot=0;
for(var i=0;i<arr.length;i ){
if(parseInt(arr[i].value))
tot = parseInt(arr[i].value);
}
document.getElementById(total_element_name).value = tot;
}
then call it with those arguments where necessary
<td><input onblur="findTotal('qty', 'total')" type="number" name="qty" id="qty"/></td>
<td><input onblur="findTotal('qty2', 'total2')" type="number" name="qty2" id="qty2"/></td>
CodePudding user response:
That is exactly what i was looking for ! I really appreciate. Thank you very much sir !