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>
function sum(id)
{
var a = $('#valuea'+id).val();
var total = sum all a values;
................
$('#totala'+id).val(parseFloat(total));
function check(id)
{
var a= $('#totala'+id).val()
var b =$('#valueb'+id).val();
if (a >= b)
{
$('#btn').show();
}
else
{
$('#btn').hide();
}
}
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