Bakti Wijaya Bakti Wijaya - 3 years ago 170
jQuery Question

How do I sum data inside nested foreach loops?

I want to sum all data from inside a foreach loop and compare this to values in an outer foreach using jquery, but I don't know how to sum all of the data points from my inner foreach.

Here is the view:

<?php $no = 1;
foreach($data as $value)
{
echo "<b>".$no."</b>";
echo "<br>";
foreach($datas as $values)
{
echo "<input type="number" id="valuea<?= $no ?>" value=".$values['myvalue']." onchange='sum(".$no.");check(".$no.")'>";
}
echo "<input type='text' id='totala"<?= $no ?>"' readonly>";
echo "<input type='text' id='valueb"<?= $no ?>"' readonly value=".$value['myvalue'].">";

}

<button type='button' id='btn'>My Button</button>


and here is the sum function:

function sum(id)
{
var a = $('#valuea'+id).val();
var total = sum all a values;
................

$('#totala'+id).val(parseFloat(total));


After summing all level 2 foreach data, the validation works like this:

if values from the inner foreach >= values on outer foreach,
then button shows else button is hidden

here is the validation jquery:


function check(id)
{
var a= $('#totala'+id).val()
var b =$('#valueb'+id).val();


This is where I am confused with the logic...it is supposed to be:

if (a >= b)
{
$('#btn').show();
}
else
{
$('#btn').hide();
}
}

Answer Source

I would put each inner foreach inputs inside of a div and give them a class, so to sum you can select them by the ones inside of that div looping them using each() function. Also, give each input a data-no with its $no, so you can easily access that value from jquery. Then, you can do the check and the sum directly inside of the jquery change() function. Something like this...

PHP:

<?php $no = 1;

foreach($data as $value)
{
    echo "<b>".$no."</b>";
    echo "<br>";

    echo "<div class=\"innerloop\">";
    foreach ($datas as $values)
        echo "<input type=\"number\" class=\"innerinput\" id=\"valuea".$no."\" data-no=\"".$no."\" value=\"".$values["myvalue"]."\" >";
    echo "</div>";

    echo "<input type=\"text\" id=\"totala".$no."\" readonly>";
    echo "<input type=\"text\" id=\"valueb".$no."\" value=\"".$value['myvalue']."\" readonly>";

}

<button type='button' id='btn'>My Button</button>

...........

JQUERY:

$('input.innerinput').change(function() {

    var $innerloop = $(this).parent('div.innerloop');
    var no = $(this).data('no');

    var total = 0;
    $innerloop.children('input.innerinput').each(function() {
        total += parseFloat($(this).val());
    });

    $('input#totala'+no).val(total);

    if (total >= $('input#valueb'+no).val())
        $('#btn').show();
    else
        $('#btn').hide();

});

I hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download