Rails 5:重新计算所选字段的总和

时间:2018-10-23 13:12:40

标签: javascript jquery ruby-on-rails

我正在尝试显示所选字段的总和,例如12 multiplied by the price

目前,我只能显示一次总和,但是当发生更改事件时,总金额不会在预览中更新。

我当前的代码:

<script>

$(function() {

  $.ajax({
    url: '<%= preload_wine_path(@wine) %>',
    dateTyp: 'json',
    success: function(data) {

      $.each(data, function(arrID, arrValue) {

      });

      $('#reservation_start_date').datepicker({
        dateFormat: 'dd-mm-yy',
        minDate: 2,
        maxDate: '5d',
        beforeShowDay: $.datepicker.noWeekends,
        onSelect: function(selected) {
          $('#preview').show();
          $('#btn_book').attr('disabled', false);

          var bottles = document.getElementById("bottles").value;
          var total = bottles * <%= @wine.price %>

          $('#reservation_bottles').text(bottles);
          $('#reservation_total').text(total);    
        }
      });
    }
  });
});

</script>

我也尝试添加addEventListener('onChange'),但仍然遇到相同的问题。

2 个答案:

答案 0 :(得分:0)

尝试:

$(".bottles").on("change", function() {
   $.ajax({
    url: '<%= preload_wine_path(@wine) %>',
    dateType: 'json',
    success: function(data) {

          var bottles = $(this).val();
          var total = bottles * <%= @wine.price %>

          $('#reservation_bottles').text(bottles);
          $('#reservation_total').text(total);    
        }
      });
    }
  });
});

答案 1 :(得分:0)

我更新了代码,发现这是一个可行的解决方案。

<script>

$(function() {

  $.ajax({
    url: '<%= preload_wine_path(@wine) %>',
    dateTyp: 'json',
    success: function(data) {

      var bottles = document.getElementById("bottles").value;
      var total = bottles * <%= @wine.price %>
      $('#reservation_bottles').text(bottles);
      $('#reservation_total').text(total);

      $('#reservation_start_date').datepicker({
        dateFormat: 'dd-mm-yy',
        minDate: 2,
        maxDate: '5d',
        beforeShowDay: $.datepicker.noWeekends,
        onSelect: function(selected) {
          $('#preview').show();
          $('#btn_book').attr('disabled', false);

          $('#bottles').on('click', function() {
          var bottles = $(this).val();
          var total = bottles * <%= @wine.price %>

          $('#reservation_bottles').text(bottles);
          $('#reservation_total').text(total.toFixed(2));

          });
        }
      });
    }
  });
});

</script>