Add dynamic fields in jQuery

0

I have the following HTML

<form id="FrmLoja" method="post" action="#">
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="valor[]" id="valor" value="0" />
  <input type="text" name="total" id="total" value="" />
</form>

I need to add all values and insert the total result without the need for a reload on the page ... This value field, is a dynamic field, where I have a btn (+) which adds a new line whenever I need , inside the array ... How can I do this sum?

    
asked by anonymous 08.05.2017 / 19:24

1 answer

1

Do this:

 $('#add').click(function() {
  $('.fields').append('<input type="text" name="valor[]" id="valor" value="0" onkeyup="sum()" />');
});

function sum()
{
  let total = 0;
   
  $('.fields input').each(function() {
      total += +$(this).val();
  });
  $('#total').val(total);
}
.fields input {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script><formid="FrmLoja" method="post" action="#">
  <div class="fields">
    <input type="text" name="valor[]" id="valor" value="0" onkeyup="sum()"/>
  </div>

  <input type="text" name="total" id="total" value="" />

  <button type="button" id="add">+</button>
</form>

NOTE: I left the event as a keyup only as an example, you can change it to onblur so that the sum is done only when the user finishes typing and focuses the field.

    
08.05.2017 / 19:38