Steven Lnds Steven Lnds - 2 months ago 9
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">

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




?>
<tr>
<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>
</tr>
<?php
$incr ++;
}
?>
<tr>
<td colspan="3">Total : </td>
<td></td>
</tr>

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

</form>


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.

Answer

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

subtotal[index].innerText

and parse it into Number using

Number(subtotal[index].innerText)

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.