Предотвратить удаление первой строки (динамической таблицы) jquery - PullRequest
0 голосов
/ 09 декабря 2018

У меня есть эта таблица, которая позволяет мне удалять / добавлять строки:

$(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>

Я пытаюсь предотвратить удаление первой строки ИЛИ, если она удалена, чтобы разрешить создание новой.

Вмой код, когда удаляется первая и единственная строка, я не могу добавить новую.

Заранее спасибо за рекомендацию.

1 Ответ

0 голосов
/ 09 декабря 2018

Ваша текущая функция удаления:

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

Я полагаю, вы ошиблись с $ ("# delete_row"). Click (function () {.

Поскольку кнопка удаления строки таблицы имеет класс btn и отсутствует элемент delete_row , я бы предложил изменить функцию удаления с помощью:

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

чтобы избежать удаления всех строк, вы можете проверить, нет ли в текущей строке родных элементов:

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

Другая проблема связана с глобальными переменными. Вы можете избежать использования такой переменной, упростив метод добавления (я удалилпоследняя пустая строка у вас ...)

$(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>
...