js-notes

by jeanmichelricher

HTML

<table>
    <thead>
         <tr>
             <th>Matière</th>
             <th>Note</th>
         </tr>       
    </thead>
    <tbody>
        <tr>
            <td>Français</td>
            <td class="right note">12</td>
        </tr>
        <tr>
            <td>Mathématiques</td>
            <td class="right note">11</td>
        </tr>
        <tr>
            <td>Physique</td>
            <td class="right note">13</td>
        </tr>
        <tr>
            <td>Anglais</td>
            <td class="right note">15</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Total</td>
            <td id="moyenne" class="right"></td>
        </tr>
    </tfoot>
 </table>

CSS

table {
    margin: 10px auto;
    border: 1px solid black;
    border-collapse: collapse;
}

td, th {
    border: 1px solid black;
}

td.right {
    text-align: right;
}

td.note {
    
}

JavaScript

function calcul_moyenne() {
	const notes = document.querySelectorAll('.note');

    // Calculatede la somme et du nombre de valeurs
    let somme= 0;
    let nombre = 0;
    notes.forEach(note => {
        somme += parseInt(note.textContent, 10) || 0; // Handle non-numeric content
        ++nombre;
    });
    
    // Calcule de la moyenne
    const moyenne = nombre > 0 ? (somme / nombre).toFixed(2) : 0;

    // Modifier la cellule d'identifiant moyenne
    const cellule_moyenne = document.getElementById('moyenne');
    cellule_moyenne.textContent = `${moyenne}`;
}


document.addEventListener('DOMContentLoaded', function () {
    console.log('The DOM is fully loaded!');
    // Your function call here
    calcul_moyenne();
});