Jquery in 循环执行一些记录计算


Jquery in loop to perform some calculation of records

我正在尝试使用 php 带来一些记录并进行一些计算。我现在正在做的是,每一行都有一个不同货币的下拉列表。当我选择每种货币时,它会计算并显示某些值。直到这里它工作正常。

我试图实现的是,如果我选择第一个货币下拉列表,它应该计算完整的记录计算,而不是选择每行的货币。我想我需要在计算行的 jquery 中执行某种循环。

小提琴

以下是货币下拉列表的 jquery 脚本部分。

$(window).load(function() {
  $(document).ready(function() {
    $("select").on('change', function() {
      var dept_number = $(this).val();
      var price = $(this).find(':selected').data('price');
      var selected = $(this).find('option:selected').text();
      if (selected == "INR") {
        $(this).closest('table').find('.total1').val($(this).closest('table').find('.total').val());
      } else {
        $(this).closest('table').find('.total1').val((($(this).closest('table').find('.total').val() * price) / $(this).closest('table').find('.inrvalue').val()).toFixed(3));
      }
      $(this).closest('table').find('.price_unit').val(($(this).closest('table').find('.total1').val() / $(this).closest('table').find('.qty').val()).toFixed(3));
    });
  });
});

我想我需要在这个jQuery中添加一些循环。任何人都可以指导我如何做到这一点。或者我需要遵循不同的步骤。

这是我根据Leonix的建议尝试的。

$(document).ready(function(){
            $(this).closest('table').find("select").each(function() {
               var dept_number = $(this).val();
               var price = $(this).find(':selected').data('price');
           
                var selected = $(this).find("select");
           
           if(selected=="INR")
            {
               $(this).closest('table').find('.total1').val($(this).closest('table').find('.total').val());
           
            } else
            {
           
           $(this).closest('table').find('.total1').val((($(this).closest('table').find('.total').val() * price) / $(this).closest('table').find('.inrvalue').val()).toFixed(3));
           }
           
               $(this).closest('table').find('.price_unit').val(($(this).closest('table').find('.total1').val()/$(this).closest('table').find('.qty').val()).toFixed(3));
           
           });
           });

在选择更改函数中,对表的所有行执行每个操作并找到下拉列表:

$(this).closest('table').find("select").each(function() {
    /* Each SELECT here, use $(this) */
})

或者,根据您的需要:

$(this).closest('table').find("select").each(function() {
    /* Each TR here, use selectInput */
    var selectInput = $(this).find("select");
})

选择在手中,使用 selectInput.val(changedSelectInput.val())changedSelectInput 是包含更改的 select 的 jquery 对象。
使用嵌套的匿名函数,请注意,它们是在对象上下文中执行的,因此 this 和 $(this) 会根据受函数影响的对象而变化。

建议:为 JS 使用特定的 css 类,作为 select.select-currency 而不是仅选择,将这些类放在您的代码中。 它将防止如此多的错误,并将节省您的时间。

注意:currency_change[] 不是有效的 ID,如果您不需要设置,请不要设置。

编辑

一些代码:https://jsfiddle.net/btpxq5ow/6/
我做了什么?

  1. 解决标签问题
  2. 修复 tbody 中的输入问题,切勿直接将其放入 tr、tbody、表中。
  3. 修复一些缩进问题
  4. 将货币更改应用于所有行
  5. 防止更改事件在无限循环中调用自身
  6. 更新时将计算应用于所有行
  7. 修复一些代码语法和性能问题

请检查您的计算是否正确,因为我修改了它,请参阅计算行总计()。
仍然有一些 html/js 错误必须修复。

您很少会从stackoverflow获取代码