Как узнать цену динамически созданных строк? - PullRequest
0 голосов
/ 20 апреля 2019

Я хочу суммировать цену всех динамически создаваемых строк и отображать их в поле общего ввода. Я пробовал некоторые вещи, но не работал для себя. Я разместил свой сценарий и изображение, которое объясняет, как это должно работать.Все работает и сохраняется в базе данных, просто нужно общее количество всех элементов.Пожалуйста, смотрите изображение для ясной концепции.Итог 1-й строки сохраняет в целом, но не работает для динамически создаваемых строк.

Изображение: Должно работать так:

Html:

   <div class="form-group">
     <label>Total</label>
      <input readonly type="text" id="total_amount" class="form-control"
       name="total_amount">
    </div>

Сценарий:

 <script>
    var counterr = 1;
    $(document).ready(function () {

        $('#unit_price,#item_quantity').change(function () {
            // alert();
            var unitPrice = $('#unit_price').val();
            // console.log(unitPrice);
            var quantity = $('#item_quantity').val();
            // console.log(quantity);

            var total = (unitPrice * quantity).toFixed(0);

            $('#total_price').val(total);
            $('#total_amount').val(total);

        });


        // Input Fields


        var maxField = 100; //Input fields increment limitation
        var addButton = $('#add_button'); //Add button selector
        var wrapper = $('.field_wrapper'); //Input field wrapper

        $(addButton).click(function (e) {
            e.preventDefault();
            counterr++;
            //Check maximum number of input fields
            if (counterr < maxField) {
                fieldHTML = makeNewRow(counterr);
                $(wrapper).append(fieldHTML); //Add field html
                // $('#department-'+counterr).select2();

                // console.log("Unit price", counterr);
                $('.unit_price' + counterr).change(function () {
                    // console.log("hello");
                    var unitPrice = $('.unit_price' + counterr).val();
                    // console.log(unitPrice);
                    var quantity = $('#item_quantity' + counterr).val();
                    // console.log(quantity);

                    var total = (unitPrice * quantity).toFixed(0);

                    $('#total_price' + counterr).val(total);


                     $('#total_price').each(function() {
                    subtotal += parseFloat($(this).val());
                    console.log('test',subtotal);
                });
                 $('#total_amount').val(subtotal);

                });


            }

        });


        //Once remove button is clicked
        $(wrapper).on('click', '.remove_button', function (e) {
            e.preventDefault();
            $(this).parent('#newrow').remove(); //Remove field html
            counterr = counterr--; //Decrement field counter
        })


    });

    function makeNewRow(counterr) {

        return '<div class="row" id="newrow">' +
            '<div class="col-md-4">' +
            '<div class="form-group">' +
            '<select onChange="getPurchasePrice(this.value);" style="background-color: #f5f6f9" id="item_name' + counterr + '" class="form-control dep"' +
            'placeholder="Enter Item" name="testing[]"' + '>' +
            '<option value = "">Select Item</option>' + '>' +
            '@foreach($items as $item)' + '>' +
            '<option value = "{{$item->id}}">{{$item->item_name}}</option>' + '>' +
            '@endforeach' + '>' +
            '</select>' +
            '</div>' +
            '</div>' +
            '<div class="col-md-2">' +
            '<div class="form-group">' +
            '<input style="background-color: #f5f6f9" type="number" id="item_quantity' + counterr + '" class="form-control"' +
            'placeholder="Enter.." name="testing[]"' + '>' +
            '</div>' +
            '</div>' +
            '<div class="col-md-2">' +
            '<div class="form-group">' +
            '<input style="background-color: #f5f6f9" type="number" id="unit_price' + counterr + '" class="unit_price' + counterr + ' form-control"' +
            'placeholder="Enter.." name="testing[]"' + '>' +
            '</div>' +
            '</div>' +
            '<div class="col-md-3">' +
            '<div class="form-group">' +
            '<input value="0" style="background-color: #f5f6f9" disabled type="text" id="total_price' + counterr + '" class="form-control"' +
            'placeholder="Total" name="testing[]"' + '>' +
            '</div>' +
            '</div>' +
            '<a style="height:40px;margin-left:25px" href="javascript:void(0);" class="btn btn-danger remove_button">X</a>' +
            '</div>'; //New input field html
    }

    /*function removeDiv(no){
        $("#testingrow-"+no).remove();
        x--;
    }*/


</script>

Ответы [ 2 ]

1 голос
/ 20 апреля 2019

Добавить функцию для пересчета итоговой суммы 'recalcGrandTotal'

var recalcGrandTotal = function() {
    var grandTotal = 0; // Declare a var to hold the grand total
    $("[id^=total_price]").each(function() { // Find all elements with an id that starts with 'total_price'
        grandTotal += parseInt($(this).val()); // Add the value of the 'total_price*' field to the grand total
      })
  $('#total_amount').val(grandTotal); // append grand total amount to the total field
}

Затем подключите эту функцию к функции пересчета «общей цены»: Найти

$('#total_price' + counterr).val(total);

Добавить после:

recalcGrandTotal();

Чтобы вычесть из общей суммы при удалении предмета, подключите эту функцию к функции удаления предмета. Найти:

counterr = counterr--; //Decrement field counter

Добавить после:

recalcGrandTotal();
0 голосов
/ 20 апреля 2019

Добавить класс с именем total_price в элемент id total_price и изменить

 $('#total_price').each(function() {
                    subtotal += parseFloat($(this).val());
                    console.log('test',subtotal);

К

$('.total_price').each(function() {
                        subtotal += parseFloat($(this).val());
                        console.log('test',subtotal);
$('#total_amount').val(subtotal);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...