根据表单中的选择更改表单中的变量

时间:2012-06-14 17:54:59

标签: javascript ruby-on-rails forms

更新日期6/21/12

我在rails中有一个类似于电子商务结帐的表单。

用户在表单中选择开始时间,结束时间,日期,时间和价格偏好(每小时,每周,每日等)。该产品已经在我转换为(每小时,每周,每天等)的数据库中设定了价格,我想根据价格偏好进行更改,然后将其与表格的其余部分一起提交。 / p>

我一直关注Ryan在dynamic select menus的截屏视频,但我不确定我的演示是如何适应我的应用程序的,因为我不希望用户只选择价格(每日/每小时/等。)

Gear has_many line_items line_items属于Gear and Carts

以下是我的代码:

齿轮模型(我已经创建了价格变量)

class Gear < ActiveRecord::Base
  attr_accessible :title, :size, :price, :sub_category_id, :user_id, :image, :image_a, :remote_image_url, :color, :year, :latefee, :cancellation, :minrental, :policy, :about, :address, :city, :state, :zip
  belongs_to :user
  belongs_to :sub_category
  has_one :category, :through => :sub_category
  has_many :comments, :dependent => :destroy 
  has_many :line_items
  has_many :calendars
  require 'carrierwave/orm/activerecord'
  mount_uploader :image, GearpicUploader
  mount_uploader :image_a, GearpicUploader
  before_destroy :ensure_not_referenced_by_any_line_item

  validates :title, presence: true
  validates :size,  presence: true
  validates :price, presence: true
  validates :sub_category_id, presence: true
  validates :user_id, presence: true

  def hourly_price
    price/24
  end

  def weekly_price
    price*7
  end

  def monthly_price
    weekly_price*4
  end
end

查看

<div class="gearside_date_top">
    <%= form_for LineItem.new do |f| %>
    <p><%= render :partial => "price" %> / 
        <%= f.select :day_or_hour, [['day', 1], ['hour', 2]], :id => 'day_or_hour' %>
    </p>
</div>      

部分参与

<em>from</em>
<span id="gear_daily" style="font-size: 190%; color: #94cbfc;">$<%= @gear.price %></span>
<span id="gear_hourly" style="font-size: 190%; color: #94cbfc; display:none;">$<%= @gear.hourly_price %></span>

的Javascript

$('#day_or_hour').change(function() {

     var $index = $('#day_or_hour').index(this);

     if($('#day_or_hour').val() = '2') { 
     $('#gear_hourly').show(); 
     } 
     else {
     $('#gear_daily').show();//else it is shown

     }
});

我似乎无法让它发挥作用。

1 个答案:

答案 0 :(得分:1)

您可以将价格放在一个部分:

<div class="gearside_date_top">
  <%= form_for LineItem.new do |f| %>
  <%= render :partial => "price" %>
  <%= f.select :day_or_hour, [['day', 1], ['hour', 2]], :id => 'day_or_hour' %>

<强> _price.html.erb

<em>from</em><span style="font-size: 190%; color: #94cbfc;">$<%= @gear.price %></span>

在你的line_item.js中,你输入代码来更新价格: 的 line_item.js

$('#day_or_hour').change(function() {
  $.get("/cart/update_price", {option: $(this).val()}, function(data) {
  }
}

cart_controller.rb 上,您可以创建调用line_item.rb total_price的方法update_price。

希望你明白。

修改

看起来像这样。

def update_price
  @gear.price = LineItem.total_price(@gear)
  render :partial => 'price'
end