Rails 3. Как добавить налог на позиции с помощью jQuery? - PullRequest
2 голосов
/ 03 февраля 2012

У меня есть модель Invoice и модель LineItem.Мне удалось вычислить итоговое значение строки, умножив цену LineItem на количество.Теперь я должен также добавить налог.

Количество и цена получены из атрибутов данных в меню выбора элемента lineitem.Теперь, как я могу добавить налог в расчет?

Это то, что у меня есть ...

<tr class="item line_item_row">
  <td style="border:0;"><%= link_to_remove_fields "X", f %></td>
  <td class="item_name_data first_column">
  <!-- the line_item_row class name is used in the jQuery function remove_fields() -->

  <%= f.select(:item_id, options_for_select(@items.map{|c| [c.name, c.id, {'data-defaultquantity'=>1,'data-price'=>c.price, 'data-description'=>c.description}]}, f.object.item_id), {:prompt => ''}, {:class=>'product', :style => 'width:105px;'}) %>

  </td>
  <td class="description">
    <%= f.text_area :description, :rows => 1, :value => f.object.description, :class => 'description' %>
  </td>

  <td class="price_data">
    <%= f.text_field :price, :size => 6, :value => (number_with_precision(f.object.price,:precision => 2)||0), :class => 'price' %>
  </td>

  <td class="quantity_data">
    <%= f.text_field :quantity, :size => 4, :class => 'qty' %>
  </td>

  <td class="tax_data">
    <%= f.collection_select 'tax_ids', Tax.all, :id, :name, {:name => 'line_item[tax_ids][]', :prompt => ''} %>
  </td>

  <td class="lineitemtotal linetotal_data" style="text-align:right;">
  </td>
</tr>

Это мой JavaScript

function remove_fields(link){
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".line_item_row").hide();
}

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  // $(link).parent().before(content.replace(regexp, new_id));
  // $('#invoice > tbody:last').append(content.replace(regexp, new_id));
  $('.add_a_line_row').before(content.replace(regexp, new_id));
}

// get invoce grand total
function getTotal(lines) {
  var total = 0;
  $.each(lines, function(){
    total += parseFloat($(this).html());
  });
  $('#total-price').html('$' + total + ' MXN');
}

function getLineItemTotals(lines){
  $.each(lines, function(){
    row_total = 0;
    var price = parseFloat($(this).find('.price').val()); // get price
    var qty = parseFloat($(this).find('.qty').val()); // get quantity
    /* Check if quantity or price are empty */
    if(!qty) qty = '0';
    if(!price) price = '0';
    row_total = price * qty; // row_total = parseFloat($(this).find('.price').val()) * parseFloat($(this).find('.qty').val());
    // $($(this).find('.lineitemtotal')).html(roundNumber(row_total,2));
    $($(this).find('.lineitemtotal')).html(row_total.toFixed(2));
  })
}

function roundNumber(num,dec){
  var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  return result;
}

// new items will be populated with default data
// /5121010/funktsiya-dlya-dobavleniya-novyh-predmetov
$(document).on("blur", ".product", function(){
  var optionElem = $(this).find(":selected")[0]; // <option value="3" data-defaultQuantity="1">product name</option>
  $(this).closest('.item').find('.qty').val(optionElem.dataset.defaultquantity); // replace quantity
  $(this).closest('.item').find('.price').val(optionElem.dataset.price); // replace price
  $(this).closest('.item').find('.description').val(optionElem.dataset.description); // replace price

  var line = $('.item');
  getLineItemTotals(line);
  var line_totals = $('.lineitemtotal');
  getTotal(line_totals);
  $('#total-price').effect('highlight',{},3000);
});

$(document).on("blur", ".price", function(){
  // price change
  var price = $('.price');
  price.blur(function(){
    var line = $('.item');
    getLineItemTotals(line);
    var line_totals = $('.lineitemtotal');
    getTotal(line_totals);
    $('#total-price').effect('highlight',{},3000);
  });
});

$(document).on("blur", ".qty", function(){
  // price change
  var qty = $('.qty');
  qty.blur(function(){
    var line = $('.item');
    getLineItemTotals(line);
    var line_totals = $('.lineitemtotal');
    getTotal(line_totals);
    $('#total-price').effect('highlight',{},3000);
  });
});

$(document).ready(function() {

  var line = $('.item');
  // so the line totals are calculated on page load
  getLineItemTotals(line);

  var line_totals = $('.lineitemtotal');
  getTotal(line_totals); // So the total is calculated on page load.

});

1 Ответ

0 голосов
/ 04 февраля 2013

Чтобы получить значение выбранного элемента в поле выбора, это:

$("#your_select_box option:selected").text(); ИЛИ $("#your_select_box option:selected").val(); в зависимости от того, хотите вы или нет value="" опции или текста ввариант.

Итак, вы захотите взглянуть на то, как ID Rails присваивает свой блок выбора (или просто ссылается на него через $(".tax_data select option:selected"), и в вашей функции getLineItemTotals добавьте искатель и добавьте налоговую стоимостьна row_total. Не забывайте свой parseFloat.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...