0

Нужно заполнить таблицу данными из input и посчитать итоговую сумму. Пробовал так:

$(document).on('change', '.input-box input', function () {
  var name = $('#name').val();
  $('.name').text(name);
  
  var lastname = $('#lastname').val();
  $('.lastname').text(lastname);
  
  var sum = $('#sum').val();
  $('.sum').text(sum);
});

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

Сумму пробовал считать так:

$('.input-box input').change(sum);
function sum(){
    let result=0;
    $('.sum').each(function(){
        let value = 0;
        if (typeof Number($(this).html()) == 'object'){
          $.each($(this).val(), function(index, val) {
            value += val*1;
          });
        } else {
          value = Number($(this).html());
        }
        result+=value*1;
    });
    $('.total').text(result);
}

Не получилось, в .total записывает "0".

    $('.addline span').on('click', function () {
        $(this).parent().before('<div class="d-flex"><div class="input-box"><input type="text" value="" id="name" placeholder="Имя"></div><div class="input-box"><input type="text" value="" id="lastname" placeholder="Фамилия"></div><div class="input-box"><input type="text" value="" id="sum" placeholder="Сумма"></div></div>');
        var index = $('.row').last().index() + 1;
        $('.total_row').before('<tr class="row"><td>' + index + '</td><td class="name"></td><td class="lastname"></td><td class="sum"></td></tr>');
    });
$(document).on('change', '.input-box input', function () {
  var name = $('#name').val();
  $('.name').text(name);
  
  var lastname = $('#lastname').val();
  $('.lastname').text(lastname);
  
  var sum = $('#sum').val();
  $('.sum').text(sum);
});


$('.input-box input').change(sum);
function sum(){
    let result=0;
    $('.sum').each(function(){
        let value = 0;
        if (typeof Number($(this).html()) == 'object'){
          $.each($(this).val(), function(index, val) {
            value += val*1;
          });
        } else {
          value = Number($(this).html());
        }
        result+=value*1;
    });
    $('.total').text(result);
}
.form {
  max-width: 540px;
  margin-bottom: 30px;
}
.d-flex, .addline {
  display: flex;
  margin-bottom: 15px;
}
.d-flex:last-child {
  margin-bottom: 0;
}
.addline {
  justify-content: center;
}
.addline span {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 25px;
  height: 25px;
  border: 1px solid black;
  border-radius: 50%;
  box-sizing: border-box;
  cursor: pointer;
}
.input-box {
  margin-right: 10px;
}
.input-box:last-child {
  margin-right: 0;
}
.ta-right {
  text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form">
  <div class="d-flex">
    <div class="input-box">
      <input type="text" value="" id="name" placeholder="Имя">
    </div>
    <div class="input-box">
      <input type="text" value="" id="lastname" placeholder="Фамилия">
    </div>
    <div class="input-box">
      <input type="text" value="" id="sum" placeholder="Сумма">
    </div>
  </div>
  <div class="addline">
    <span>+</span>
  </div>
</div>
<table border="1">
  <tr>
    <th>№</th>
    <th>Имя</th>
    <th>Фамилия</td>
    <th>Сумма</td>
  </tr>
  <tr class="row">
    <td>1</td>
    <td class="name"></td>
    <td class="lastname"></td>
    <td class="sum"></td>
  </tr>
  <tr class="total_row">
    <td class="ta-right" colspan="3">Итого</td>
    <td class="total"></td>
  </tr>
</table>

1 ответ 1

1

Код совсем не оптимизирован, но для понимания пойдет. Скорректировал скрипт и HTML.

$('.addline span').on('click', function () {
        var index = $('.row').last().index() + 1;
        
        $(this).parent().before('<div class="d-flex" data-id="'+index+'"><div class="input-box"><input type="text" value="" class="name" placeholder="Имя"></div><div class="input-box"><input type="text" value="" class="lastname" placeholder="Фамилия"></div><div class="input-box"><input type="text" value="" class="sum"  placeholder="Сумма"></div></div>');
        
        $('.total_row').before('<tr class="row" id="row'+index+'"><td>' + index + '</td><td class="name"></td><td class="lastname"></td><td class="sum"></td></tr>');
    });
    
    $(document).on('change', '.input-box input', function () {    
      const id = $(this).parents('.d-flex').data('id');
      const row = $('#row'+id);
      
      $(row).find('.name').html( $(this).parents('.d-flex').find('.name').val() );
      $(row).find('.lastname').html( $(this).parents('.d-flex').find('.lastname').val() );
      $(row).find('.sum').html( $(this).parents('.d-flex').find('.sum').val() );
      
      if( $(this).hasClass('sum') ) {
        sum();
    }
    });

    
    function sum(){
        let result=0;
        $('tr.row .sum').each(function(){
            const current = Number($(this).html()) || 0;
            console.log(current);
            result += current;
        });
        
        $('.total').text(result);
    }
.form {
  max-width: 540px;
  margin-bottom: 30px;
}
.d-flex, .addline {
  display: flex;
  margin-bottom: 15px;
}
.d-flex:last-child {
  margin-bottom: 0;
}
.addline {
  justify-content: center;
}
.addline span {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 25px;
  height: 25px;
  border: 1px solid black;
  border-radius: 50%;
  box-sizing: border-box;
  cursor: pointer;
}
.input-box {
  margin-right: 10px;
}
.input-box:last-child {
  margin-right: 0;
}
.ta-right {
  text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form">
  <div class="d-flex" data-id="1">
    <div class="input-box">
      <input type="text" value="" class="name" placeholder="Имя">
    </div>
    <div class="input-box">
      <input type="text" value="" class="lastname" placeholder="Фамилия">
    </div>
    <div class="input-box">
      <input type="text" value="" class="sum" placeholder="Сумма">
    </div>
  </div>
  <div class="addline">
    <span>+</span>
  </div>
</div>
<table border="1">
  <tr>
    <th>№</th>
    <th>Имя</th>
    <th>Фамилия</td>
    <th>Сумма</td>
  </tr>
  <tr class="row" id="row1">
    <td>1</td>
    <td class="name"></td>
    <td class="lastname"></td>
    <td class="sum"></td>
  </tr>
  <tr class="total_row">
    <td class="ta-right" colspan="3">Итого</td>
    <td class="total">0</td>
  </tr>
</table>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.