Home > database >  jquery sum column if row checked
jquery sum column if row checked

Time:10-12

I have this table into a modal form:

<div class="form-group">
    <!-- Record list -->
    <table id="tabscarichi" class="table table-bordered table-striped" style='border-collapse: collapse;' >
        <tr style='background: whitesmoke;'>
            
            <th>Check</th>
            <th>Id</th>
            <th>Formulario</th>
            <th>EER</th>
            <th>Data FR</th>
            <th>Q.tà</th>
        </tr>

            <?php 
            $query = "SELECT * FROM registro_c_s where stato_carico='1'";
            $result = mysqli_query($conn,$query);

            while($row = mysqli_fetch_array($result) ){
                $id = $row['id'];
                $fr = $row['formulario'];
                $data = $row['data_fr'];
                $eer = $row['codice_eer'];
                $qta = $row['quantità'];
                $stato = $row['stato_carico'];
            ?>
        <tr>

            <!-- Checkbox -->
            <td><input type='checkbox' class="box" name='update[]' value='<?= $id ?>' ></td>
            
            <td><?= $id ?></td>
            <td><?= $fr ?></td>
            <td><?= $eer ?></td>
            <td><?= $data ?></td>
            <td class="qta_scarichi"><?= $qta ?></td>

        </tr>
            <?php

            }
            
            ?>
    </table>
</div> 

I'm trying to write a script to sum values of class .qta_scarichi and reporting it in another input number with .qtas class.

I tried this:

$('.box').change(function(){
   var total = 0;
   $('.box:checked').each(function(){
        total =parseFloat($(this).parent().next('td').find('.qta_scarichi').text());
   });
   $('#qtà').val(total); 
});

But when i check some rows..nothing happen.. #qtà is the id of the input number that i want to fill..

CodePudding user response:

Problem found! in table with id="tabscarichi" i have the following script:

$(function() { 
$('#tabscarichi').hide(); 
$('#tipo').change(function(){ 
if($('#tipo').val() == 'scarico') { 
$('#tabscarichi').show(); 
console.log('0'); } 
else { $('#tabscarichi').hide(); 
} }); }); </script> ``` 

i choose to show the table with a select... if i disable the script.. the css selector works! But i don't understand why..

CodePudding user response:

$(this).parent().next('td') just selects <td><?= $id ?></td>, which doesn't contain .qta_scarichi.

Use $(this).closest('tr').find('.qta_scarichi').

I suspect you may have intended ".siblings('td'). .next()` only selects the immediately following element.

  • Related