Add dynamic fields in jQuery

Asked

Viewed 1,411 times

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 the 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 (+) that adds a new line whenever needed, inside the array... How can I make this sum?

1 answer

1


Do it like 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>
<form id="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 keyup only as an example, you can change it to onblur so that the sum is done only when the user finishes typing and take the focus of the field.

  • Hi @Juniornunes, I tried creating this example in jsfield https://jsfiddle.net/u590wvLz/ but it didn’t work

  • @Andrébaill It was problem with the declaration of function sum, ajeitei lá: https://jsfiddle.net/u590wvLz/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.