Steven Lnds Steven Lnds - 3 months ago 15
PHP Question

Javascript calcul total in dynamically tab

I have short problem.

In my form I have multi-input and where the user change the values.

<div id="contenu">
<h2>Renseigner ma fiche de frais du mois <?php echo $numMois."-".$numAnnee ?></h2>

<form method="POST" action="index.php?uc=gererFrais&action=validerMajFraisForfait">
<div class="corpsForm">

<legend>Eléments forfaitisés
<table width=100%>
<td>Montant unitaire</td>
<td>Montant total</td>

<td width=20%><?php echo $libelle ?></td>
<td width=20%><input type="text" id="<?php echo 'idFrais'.$incr; ?>" name="lesFrais[<?php echo $idFrais?>]" size="10" min="0" autocomplete="off" maxlength="30" value="<?php echo $quantite?>" onkeyup="calculer(this)">
<td width=20%><input type="text" id="<?php echo 'montant'.$incr; ?>" value="<?php echo $montant ?>" disabled></td>
<td id='subtotal<?php echo $incr;?>' width=20%><?php echo $quantite*$montant; ?></td>
$incr ++;
<td colspan="3">Total : </td>

<div class="piedForm">
<input id="ok" type="submit" value="Valider" size="20" />
<input id="annuler" type="reset" value="Effacer" size="20" />


I want add one line where the total of the col "Montant total" has executed.

Exemple :
enter image description here

And the calcul has been executed direct, no refresh.


First of all instead of using ID for subtotal use Class - subtotal. Then all you have to do is query all of those elements using

querySelectorAll('.subtotal') or $('.subtotal')

and store the resulting array (in jQuery a jQuery object like array) into a variable. Then add events to the quantity input fields and call a function which will iterate over all of the elements in the previously stored array and convert the text stored in them (which was generated using your calculer function) which can be accessed using


and parse it into Number using


and check if the resulting number is NaN (Not a Number) or not using isNaN() function. If not add to a local total variable and write the result in the end.

Hope this helps.

Here is the code -

function CalculateTotal(e) {
        var subtotal = querySelectorAll('.subtotal');
        var subtotalCount = subtotal.length;
        var subtotalValue;
        var total = 0;
        for (var i = 0; i < subtotalCount; i++) {
            subtotalValue = Number(subtotal[i].textContent);
            if (!isNaN(subtotalValue)) total += subtotal;
        // Set the total element's textContent here.

Call the above function at the end of your calculer function.