Search code examples
jqueryhtmldynamic-tables

Prevent first row (dynamic table) from being deleted jquery


i have this table that enables me to delete / add rows:

$(document).ready(function(){
    var i=1;
    $("#add_row").click(function(){b=i-1;


        $('#addr'+i).html($('#addr'+b).html()).find('td:first-child').html(i+1);
        $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
        i++; 
    });
    $("#delete_row").click(function(){
        if(i>1){
        $("#addr"+(i-1)).html('');
        i--;
        }
        calc();
    });

    $('#tab_logic tbody').on('keyup change',function(){
        calc();
    });


});

function calc()
{
    $('#tab_logic tbody tr').each(function(i, element) {
        var html = $(this).html();
        if(html!='')
        {
            var qty = $(this).find('.qty').val();
            var price = $(this).find('.price').val();
            $(this).find('.total').val(qty*price);

            calc_total();
        }
    });
}

function calc_total()
{
    total=0;
    $('.total').each(function() {
        total += parseInt($(this).val());
    });
    $('#sub_total').val(total.toFixed(2));
    }

$(document).on('click', '.btn', function() {
    $(this).parent().parent('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row clearfix">
    <div class="col-md-12">
      <table class="table table-bordered table-hover" id="tab_logic">
        <thead>
          <tr>
            <th class="text-center"> # </th>
            <th class="text-center"> Product </th>
            <th class="text-center"> Qty </th>
            <th class="text-center"> Price </th>
            <th class="text-center"> Total </th>
             <th class="text-center">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr id='addr0'>
            <td>1</td>
            <td><input type="text" name='product[]'  placeholder='Enter Product Name' class="form-control"/></td>
            <td><input type="number" name='qty[]' placeholder='Enter Qty' class="form-control qty" step="0" min="0"/></td>
            <td><input type="number" name='price[]' placeholder='Enter Unit Price' class="form-control price" step="0.00" min="0"/></td>
            <td><input type="number" name='total[]' placeholder='0.00' class="form-control total" readonly/></td>
            <td >
                <button class="btn">
                    <i class="fa fa-trash-o"></i> Delete
                </button>
            </td>
          </tr>
          <tr id='addr1'></tr>
        </tbody>
      </table>
    </div>
  </div>
  <div class="row clearfix">
    <div class="col-md-12">
      <button id="add_row" class="btn btn-default pull-left">Add Row</button>

    </div>
  </div>
  <div class="row clearfix" style="margin-top:20px">
    <div class="pull-right col-md-4">
      <table class="table table-bordered table-hover" id="tab_logic_total">
        <tbody>


          <tr>
            <th class="text-center">Grand Total</th>
            <td class="text-center"><input type="number" name='total_amount' id="total_amount" placeholder='0.00' class="form-control" readonly/></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

I am trying to prevent the first row from being delete OR if it is deleted to enable the creation of a new one.

In my code, when the first and only row is deleted, i cannot add a new one.

Thanks in advance for your recommandation.


Solution

  • Your current delete function is:

    $(document).on('click', '.btn', function() { 
    

    I assume you made confusion with $("#delete_row").click(function(){.

    Because your table row delete button has a btn class and there is no delete_row element I would suggest to change your delete function with:

    $('#tab_logic').on('click', '.btn', function(e) {
    

    In order to avoid to remove all rows you may check if current line has no siblings:

    if ($(this).closest('tr').siblings().length > 0) {
    

    Another issue is related to global variables. You can avoid to use such a variable by simplifying the adding method (I removed the last empty row you have...)

    $(document).ready(function(){
        $("#add_row").on('click', function(e) {
            var i = +$('#tab_logic tbody tr:last td:first').text();
            var clonedRow = $('#tab_logic tbody tr:last').clone()
                    .find('td:first').text(i+1).closest('tr').attr('id', 'addr' + i)
                    .find('input').val('').closest('tr');
    
            $('#tab_logic tbody').append(clonedRow);
        });
    
        $('#tab_logic').on('click', '.btn', function(e) {
            if ($(this).closest('tr').siblings().length > 0) {
                $(this).closest('tr').remove();
                calc_total();
            }
        });
    
        $('#tab_logic tbody').on('keyup change',function(e) {
            calc();
        });
    });
    
    function calc()
    {
        $('#tab_logic tbody tr').each(function(i, element) {
            var html = $(this).html();
            if(html!='')
            {
                var qty = $(this).find('.qty').val();
                var price = $(this).find('.price').val();
                $(this).find('.total').val(qty*price);
    
                calc_total();
            }
        });
    }
    
    function calc_total()
    {
        total=0;
        $('.total').each(function() {
            total += parseInt($(this).val());
        });
        //
        // from sub_totalto total_amount
        //
        $('#total_amount').val(total.toFixed(2));
    }
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12">
                <table class="table table-bordered table-hover" id="tab_logic">
                    <thead>
                    <tr>
                        <th class="text-center"> # </th>
                        <th class="text-center"> Product </th>
                        <th class="text-center"> Qty </th>
                        <th class="text-center"> Price </th>
                        <th class="text-center"> Total </th>
                        <th class="text-center">Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr id='addr0'>
                        <td>1</td>
                        <td><input type="text" name='product[]'  placeholder='Enter Product Name' class="form-control"/></td>
                        <td><input type="number" name='qty[]' placeholder='Enter Qty' class="form-control qty" step="0" min="0"/></td>
                        <td><input type="number" name='price[]' placeholder='Enter Unit Price' class="form-control price" step="0.00" min="0"/></td>
                        <td><input type="number" name='total[]' placeholder='0.00' class="form-control total" readonly/></td>
                        <td >
                            <button class="btn">
                                <i class="fa fa-trash-o"></i> Delete
                            </button>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="row clearfix">
            <div class="col-md-12">
                <button id="add_row" class="btn btn-default pull-left">Add Row</button>
    
            </div>
        </div>
        <div class="row clearfix" style="margin-top:20px">
            <div class="pull-right col-md-4">
                <table class="table table-bordered table-hover" id="tab_logic_total">
                    <tbody>
    
    
                    <tr>
                        <th class="text-center">Grand Total</th>
                        <td class="text-center"><input type="number" name='total_amount' id="total_amount" placeholder='0.00' class="form-control" readonly/></td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>