dynamic forms multiple input fields calculate

后端 未结 2 877
庸人自扰
庸人自扰 2020-12-21 19:35

I need to add form fields dynamically. Each group of input values contain 3 fields, quantity, price, and total. Every time I insert nu

2条回答
  •  渐次进展
    2020-12-21 20:16

    Here is the solution:

    FIRST: Added JQuery

    SECOND: Corrected the method to calculate. It should multiply instead of making sum if you want quantity * price. Review my changes

    THIRD: Added a number on each ID and in the append method.

    FOURTH: Changed calculate method to carry the id

    THIRD: Commented the timer you created, and called the method that calculates the final value inside the JQUERY event "change" of the inputs. This way, you are not processing forever (even when nothing changed) and it´s only calculated when the change event is fired

    Hope it helps

    $(document).ready(function() {
      var i = 0;
      $("#quantity-" + i).change(function() {
        upd_art(i)
      });
      $("#price-" + i).change(function() {
        upd_art(i)
      });
    
    
      $('#add').click(function() {
        i++;
        $('#articles').append('   ');
    
        $("#quantity-" + i).change(function() {
          upd_art(i)
        });
        $("#price-" + i).change(function() {
          upd_art(i)
        });
    
    
      });
    
    
      $(document).on('click', '.btn_remove', function() {
        var button_id = $(this).attr("id");
        $('#row' + button_id + '').remove();
      });
    
      $('#submit').click(function() {
        alert($('#add_name').serialize()); //alerts all values           
        $.ajax({
          url: "wwwdb.php",
          method: "POST",
          data: $('#add_name').serialize(),
          success: function(data) {
            $('#add_name')[0].reset();
          }
        });
      });
    
      function upd_art(i) {
        var qty = $('#quantity-' + i).val();
        var price = $('#price-' + i).val();
        var totNumber = (qty * price);
        var tot = totNumber.toFixed(2);
        $('#total-' + i).val(tot);
      }
    
    
    
      //  setInterval(upd_art, 1000);
    });
    
    
    
    
      
      
      
    
    
    
      


    title

提交回复
热议问题