ikiK
ikiK

Reputation: 6532

Dynamic table if checkbox is unchekd empty() the td cell with JS

I have dynamic table that in one td passes php vales of prices and on end of the table is sum of those prices. There is also a checkbox in every row default checked. I need to empty the content of row where checkbox is unchecked so it removes that price value out of sum calculation.

Question, will that even remove that value? I know setting the td field to hide does not.

Value cell:

<td style="width:10%" class="rowDataSd" id="value">
    <?php echo 
    str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);

    ?>
</td>

Checkbox cell:

<td style="width:3%">
<input class="w3-check" type="checkbox" checked="checked" id="remove" name="uvrsti" value="<?php echo $row['rad_id']?>">
</td>

I tried with this but nothing happens with no errors:

      $(document).ready(function(){
    if($("#remove").is(':checked')) {
        $("#value").show();
    } else {
        $("#value").empty();
    }
     });

I can pass the unique values into each checkbox and value element into id's like:

id="<?php echo $row['rad_id']?>"

. So they tie each other but don't know how to say in JS to empty those elements.

I was also thinking something along the lines of, if on some row checkbox is unchecked empty closest td with id="value". My guess is that would be best solution but I don't know how to write it.

Or even if checkbox is unchecked remove css class .rowDataSd to closest td with id="vale" based on whom calculation is made. Sum script:

       var totals=[0,0,0];
        $(document).ready(function(){

            var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");

            $dataRows.each(function() {
                $(this).find('.rowDataSd').each(function(i){        
                    totals[i]+=parseFloat( $(this).html());
                });
            });
            $("#sum_table td.totalCol").each(function(i){  
                $(this).html('<span style="font-weight: bold;text-shadow: 0.5px 0 #888888;">'+totals[i].toFixed(2)+' kn</span>');
            });

        });

enter image description here As seen on picture need to remove row out of calculation if checkbox is unchecked. Keep in mind I dont want to delete to row, just remove it our of calculation. Any help with how to approach this is appreciated.

Upvotes: 1

Views: 581

Answers (2)

Twisty
Twisty

Reputation: 30893

Here is a basic example.

$(function() {
  function getPrice(row) {
    var txt = $(".price", row).text().slice(1);
    var p = parseFloat(txt);
    return p;
  }

  function calcSum(t) {
    var result = 0.00;
    $("tbody tr", t).each(function(i, r) {
      if ($("input", r).is(":checked")) {
        result += getPrice(r);
      }
    });
    return result;
  }

  function updateSum(tbl) {
    var t = calcSum(tbl);
    $("tfoot .total.price", tbl).html("$" + t.toFixed(2));
  }

  updateSum($("#price-list"));

  $("#price-list input").change(function() {
    updateSum($("#price-list"));
  });
});
#price-list {
  width: 240px;
}

#price-list thead th {
  width: 33%;
  border-bottom: 1px solid #ccc;
}

#price-list tfoot td {
  border-top: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="price-list">
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
      <th>&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="item name">Item 1</td>
      <td class="item price">$3.00</td>
      <td><input type="checkbox" checked /></td>
    </tr>
    <tr>
      <td class="item name">Item 2</td>
      <td class="item price">$4.00</td>
      <td><input type="checkbox" checked /></td>
    </tr>
    <tr>
      <td class="item name">Item 3</td>
      <td class="item price">$5.00</td>
      <td><input type="checkbox" checked /></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td class="total price">$0.00</td>
      <td>&nbsp;</td>
    </tr>
  </tfoot>
</table>

Upvotes: 2

PeterKA
PeterKA

Reputation: 24638

It all boils down to setting up an event handler for the checkboxes. The event handler should perform the following:

  • Track the checkbox change event for all checkboxes and the DOM ready event
  • Calculate the total of all rows with checkbox checked
  • Set the total to the total element
  • It call also perform any desired changes on the unchecked row .. not done in sample code below

THE CODE

$(function() { 
    $('.select').on('change', function() {
        let total = $('.select:checked').map(function() {
            return +$(this).parent().prev().text();
        })
        .get()
        .reduce(function(sum, price) {
            return sum + price;
        });
        $('#total').text( total );
    })
    .change();//trigger the change event on DOM ready
});

THE SNIPPET

$(function() {
    $('.select').on('change', function() {
        let total = $('.select:checked').map(function() {
            return +$(this).parent().prev().text();
        })
        .get()
        .reduce(function(sum, price) {
            return sum + price;
        });
        $('#total').text( total );
    })
    .change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
  <tr>
    <th>Item</th>
    <th>Price</th>
    <th>Select</th>
  </tr>
 </thead>
 <tbody>
  <tr>
    <td>Item 1</td>
    <td>1000</td>
    <td><input type="checkbox" class="select" checked></td>
  </tr>
  <tr>
    <td>Item 2</td>
    <td>1200</td>
    <td><input type="checkbox" class="select" checked></td>
  </tr>
  <tr>
    <td>Item 3</td>
    <td>800</td>
    <td><input type="checkbox" class="select" checked></td>
  </tr>
  <tr>
    <td>Item 4</td>
    <td>102000</td>
    <td><input type="checkbox" class="select" checked></td>
  </tr>
</tbody>
</table>

<span>TOTAL</span><span id="total"></span>

Upvotes: 1

Related Questions