【问题标题】:Calculate the total of item quantity into item price with dynamic HTML input fields using jQuery使用 jQuery 使用动态 HTML 输入字段计算项目总数量到项目价格
【发布时间】:2019-01-24 09:00:32
【问题描述】:

我想使用 jQuery 计算商品价格乘以商品数量的总和。一旦我输入了它应该用数量计算的金额并给出总金额,我就会使用动态 HTML 输入字段。请看下面的代码

我的 HTML 代码

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".add_new_field"); //Fields wrapper
    var add_button      = $(".add_another_product"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="add_new_field"><div class="row"><div class="col-md-4"><div class="form-group"><label class="col-form-label"> Enter Product Name</label><input type="text" class="form-control" name="pname[]" placeholder="Product Name"  tabindex="1"/></div></div><div class="col-md-4"><div class="form-group"><label class="col-form-label"> No. of Pieces</label><input type="text" class="form-control" name="pcount[]" placeholder="Product Inventory" tabindex="2" /></div></div><div class="col-md-3"><div class="form-group"><label class="col-form-label"> Estimated Amount</label><input type="text" class="form-control" name="estamount[]" placeholder="Product Inventory" tabindex="2" /></div><p>Amount: <span id="Amount"></span></p></div><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

$('#EstmTotal').blur(function() {

  $('.add_new_field').each(function() {
    $(this).find('#Amount').html($('#PCount(0)', this).val() * $('#EstmTotal(0)', this).val());
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
        <label class="col-form-label"> Enter Product Name</label>
        <input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name" />
      </div>
    </div>

    <div class="col-md-4">
      <div class="form-group">
        <label class="col-form-label"> No. of Pieces</label>
        <input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items" />
      </div>
    </div>

    <div class="col-md-3">
      <div class="form-group">
        <label class="col-form-label"> Estimated Amount</label>
        <input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" />
      </div>
      <p>Amount: <span id="Amount"></span></p>
    </div>
    <!--<div class="col-md-1 removebtn"><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div>-->

  </div>
</div>

<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

请查看图片以更好地理解问题

总是有讨论的选择

【问题讨论】:

  • 您是否收到错误或意外输出?
  • 我没有得到任何结果

标签: javascript jquery html


【解决方案1】:

这里有完整的代码,请试试这个。它将根据您的要求工作。

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  ></script>
<script type="text/javascript">
    function calculate(id){ console.log(id);
        // $('#EstmTotal').on('blur',function(){
        $(id).parents('.add_new_field').each(function() {
            var count = $(this).find("#PCount").val();
            var amount = $(this).find("#EstmTotal").val();
            $(this).find('#Amount').html(count*amount);
        });

    // });
    }
    $(document).ready(function(){

        $(".add_another_product").on('click',function(){
            var html = '<div class="add_new_field">';
                html += '<div class="row">'; 
                html += '<div class="col-md-4">';
                html += '<div class="form-group">';    
                html += '<label class="col-form-label"> Enter Product Name</label>';
                html += '<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name"/></div></div>';
                html += '<div class="col-md-4"><divclass="form-group"><label class="col-form-label"> No. of Pieces</label>';
                html += '<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items"/>';
                html += '</div></div>';

                html += '<div class="col-md-3">';
                html += '<div class="form-group">';    
                html += '<label class="col-form-label"> Estimated Amount</label><input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" onblur="calculate(EstmTotal)" />';
                html += '</div><p>Amount: <span id="Amount"></span></p></div>'; 
                html += '</div></div>';
            $(this).before(html);
        })
    })  
</script>
</head>
<body>
    <div class="add_new_field"> 
            <div class="row"> 
                <div class="col-md-4">
                    <div class="form-group">    
                        <label class="col-form-label"> Enter Product Name</label>
                        <input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name"/>
                    </div>
                </div> 

                <div class="col-md-4">
                    <div class="form-group">    
                        <label class="col-form-label"> No. of Pieces</label>
                        <input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items"/>
                    </div>
                </div> 

                <div class="col-md-3">
                    <div class="form-group">    
                        <label class="col-form-label"> Estimated Amount</label>
                        <input type="text" class="form-control" name="estamount[]" id="EstmTotal" onblur="calculate(EstmTotal)" placeholder="Estimated Amount of Each"/>
                    </div>
                    <p>Amount: <span id="Amount"></span></p>
                </div> 
                <!--<div class="col-md-1 removebtn"><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div>-->

               </div>
            </div>

            <button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

</body>
</html>

【讨论】:

  • 我已经检查过这是否适用于多行。
  • 在文档上设置事件委托是个坏主意。
  • 为什么会磨损?
  • 考虑到性能,最好在尽可能少的选择上执行此操作。
【解决方案2】:

我稍微更改了您的代码。现在它检查两个元素的模糊事件,并检查两者是否都有值。如果两者都有,则设置计算值。如果不是,我会清空 div。

还将值解析为浮点数。如果您愿意,可以将其更改为整数。对数字的键入检查对于整数将是相同的。我将数字向下舍入到小数点后两位,主要是为了解决浮点数精度问题。

最后,因为我认为您将能够动态创建更多行,所以我制作了由您的 .add_new_field 元素委托的模糊事件。这假设您的
.add_new_field 是一个静态元素。如果不将其更改为行的最近的静态父级。为此,我还将一些 id 选择器更改为类选择器,因为 id 需要是唯一的。

$('.add_new_field').on('blur', '.EstmTotal, .PCount', function() {
  $(this).closest('.row').each(function() {
    var pcCount = parseFloat($(this).find('.PCount', this).val());
    var estTotal = parseFloat($(this).find('.EstmTotal', this).val());

    if (typeof pcCount === 'number' && pcCount && typeof estTotal === 'number' && estTotal) {
      var calculatedValue = pcCount * estTotal;
      calculatedValue = Math.round(calculatedValue * 100) / 100;
      $(this).find('.Amount').text(calculatedValue);
    } else {
      $(this).find('.Amount').text('');
    }
  });
});

$('.add_another_product').on('click', function(){
  $('.add_new_field').append($('.row').first().clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
        <label class="col-form-label"> Enter Product Name</label>
        <input type="text" class="form-control" name="pname[]" placeholder="Product Name" />
      </div>
    </div>

    <div class="col-md-4">
      <div class="form-group">
        <label class="col-form-label"> No. of Pieces</label>
        <input type="text" class="form-control PCount" name="pcount[]" placeholder="No.Of Items" />
      </div>
    </div>

    <div class="col-md-3">
      <div class="form-group">
        <label class="col-form-label"> Estimated Amount</label>
        <input type="text" class="form-control EstmTotal" name="estamount[]" placeholder="Estimated Amount of Each" />
      </div>
      <p>Amount: <span class="Amount"></span></p>
    </div>
    <!--<div class="col-md-1 removebtn"><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div>-->

  </div>
</div>

<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

【讨论】:

    【解决方案3】:
    $('#EstmTotal').blur(function(){
    
            $('.add_new_field').each(function() {
                $(this).find('#Amount').html($('#PCount').val()*$('#EstmTotal').val());
            });
    
    });
    

    JsFiddle source

    【讨论】:

      【解决方案4】:

      我对您的代码进行了以下更改,您可以在其中找到数组中的第一个元素。你会得到想要的结果

      $('#EstmTotal').blur(function() {
      
        $('.add_new_field').each(function() {
          var elem = $($('#PCount')[0]).val();
          var elem2 = $($('#EstmTotal')[0]).val();
          $(this).find('#Amount').html(elem * elem2);
        });
      
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div class="add_new_field">
        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label class="col-form-label"> Enter Product Name</label>
              <input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name" />
            </div>
          </div>
      
          <div class="col-md-4">
            <div class="form-group">
              <label class="col-form-label"> No. of Pieces</label>
              <input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items" />
            </div>
          </div>
      
          <div class="col-md-3">
            <div class="form-group">
              <label class="col-form-label"> Estimated Amount</label>
              <input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" />
            </div>
            <p>Amount: <span id="Amount"></span></p>
          </div>
          <!--<div class="col-md-1 removebtn"><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div>-->
      
        </div>
      </div>
      
      <button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

      【讨论】:

        【解决方案5】:

        不要对多个元素使用相同的 id,用户 class 而不是 id。请参阅下面的代码以获取金额

        $(function(){
           $(document).on("blur", "div.row .col-md-3 input[name='estamount[]']", function(){
              var $row = $(this).closest('.row'); // get parent row
              var est = $(this).val(); // read estimante
              var count = $row.find('input[name="pcount[]"]').val(); // read count
              $row.find('span.Amount').html(est*count); // put product
           });
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div class="add_new_field"> 
                    <div class="row"> 
                        <div class="col-md-4">
                            <div class="form-group">    
                                <label class="col-form-label"> Enter Product Name</label>
                                <input type="text" class="form-control" name="pname[]" placeholder="Product Name"/>
                            </div>
                        </div> 
        
                        <div class="col-md-4">
                            <div class="form-group">    
                                <label class="col-form-label"> No. of Pieces</label>
                                <input type="text" class="form-control" name="pcount[]" placeholder="No.Of Items"/>
                            </div>
                        </div> 
        
                        <div class="col-md-3">
                            <div class="form-group">    
                                <label class="col-form-label"> Estimated Amount</label>
                                <input type="text" class="form-control" name="estamount[]" placeholder="Estimated Amount of Each"/>
                            </div>
                            <p>Amount: <span class="Amount"></span></p>
                        </div> 
                        <!--<div class="col-md-1 removebtn"><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div>-->
        
                       </div>
                    </div>
        
                    <button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

        【讨论】:

        • 谢谢你帮助我,但这是添加新字段后的第一个,它不起作用
        • 在添加新字段时遵循相同的 html 结构,删除 id 并遵循类。在我的代码中,我删除了 id="Amount" 并将其设为 class="Amount",其他输入保持名称相同
        • 也许你是对的,但第二行的金额即使在修改后也没有显示
        • 对不起,我的错误我没有更改 jquery 添加脚本。感谢它工作得很好
        • 在文档上设置事件委托是个坏主意。假设.add_new_field 是静态div,最好在.add_new_field 上执行。
        猜你喜欢
        • 2019-06-09
        • 2021-12-07
        • 2014-04-03
        • 1970-01-01
        • 2015-10-29
        • 1970-01-01
        • 2021-08-04
        • 1970-01-01
        • 2013-06-02
        相关资源
        最近更新 更多