Как суммировать всю цену формы ввода динамической таблицы и добавить значение в новый тип ввода?

Это моя форма ввода динамической таблицы.

<table id = "calculate">
<tr>
  <th>Price</th>
</tr>

 <tbody data-role = "dynamic-fields">
   <tr class = "form-inline">
  <td>
     <div class = "input-group">
      <input type = "text" name = "price[]" class = "form-control">
      </div>
   </td>
   <td>
      <div class = "input-group">
       <button class = "btn btn-primary btn-sm" data-role = "add">
         Add
       </button>
     </div>
    </td>
   </tr>
 </tbody>
</table>

<input type = "text" name = "total_price" id = "total_price">

Это jquery, который добавляет новую форму в таблицу, когда я нажимаю кнопку

 $(document).on(
        'click',
        '[data-role = "dynamic-fields"] > .form-inline [data-role = "add"]',
        function(e) {
            e.preventDefault();
            var container = $(this).closest('[data-role = "dynamic-fields"]');
            new_field_group = container.children().filter('.form-inline:first-child').clone();
            new_field_group.find('input').each(function(){
                $(this).val('');
            });
            container.append(new_field_group);
           }
    );

Теперь я хочу ввести много цен, нажав кнопку «Добавить», и вся цена должна суммироваться и добавляться в total_price.

$(document).on('change paste keyup', " input[name='price[]']", function(){
   updatetotalprice($(this));
});

function updatetotalamount(selector) {
  $parent = selector.parent('.input-group').parent('td').parent('tr');    [...$parent.querySelectorAll("tr")].forEach(row => {
   $("[name=amount[]]").val()= total;
    $("#total_price").val(total.toFixed(2));
 
})
  
}
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
0
0
77
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Используйте приведенный ниже код скрипта:

<script>

    $(document).on(
        'click',
        '[data-role = "dynamic-fields"] > .form-inline [data-role = "add"]',
        function(e) {
            e.preventDefault();
            var container = $(this).closest('[data-role = "dynamic-fields"]');
            new_field_group = container.children().filter('.form-inline:first-child').clone();
            new_field_group.find('input').each(function(){
                $(this).val('');
            });
            container.append(new_field_group);
        }
    );
    function updatetotalamount(selector) {
        let $parent = selector.closest('tbody'),
            total = 0;
        [...$parent[0].querySelectorAll("tr")].forEach(row => {
            console.info(($(row).find('input[name = "price[]"]')).val());
            if (($(row).find('input[name = "price[]"]')).val() !== ''){
                total += parseInt( ($(row).find('input[name = "price[]"]')).val() );
                $("#total_price").val(total);
            }
        })
    }

    $(document).on('change paste keyup', " input[name='price[]']", function(){
        updatetotalamount($(this));
    });
</script>

Удивительно !! 1 Большое спасибо.

Beginner Coder 21.12.2020 12:07

Другие вопросы по теме