当我点击句点的下拉值时,它应自动显示rate_of_interest的文本框值。
这是我计算兴趣值的模型代码:
before_save :calculate_value
def calculate_value
if self.age >= 75 && self.no_of_year == 5
self.interest_rate == 11.75
elsif self.age >= 75 && self.no_of_year == 3
self.interest_rate == 11.5
elsif self.age >= 75 && self.no_of_year == 2
self.interest_rate == 11
elsif self.age >= 75 && self.no_of_year == 1
self.interest_rate == 10.5
elsif self.age >= 58 && self.age <= 75 && self.no_of_year == 5
self.interest_rate == 11.75
elsif self.age >= 58 && self.age <= 75 && self.no_of_year == 4
self.interest_rate == 11.5
elsif self.age >= 58 && self.age <= 75 && self.no_of_year == 3
self.interest_rate == 11
elsif self.age >= 58 && self.age <= 75 && self.no_of_year == 2
self.interest_rate == 10.5
elsif self.age >= 58 && self.age <= 75 && self.no_of_year == 1
self.interest_rate == 10
elsif self.age >= 75 && self.no_of_year == 4
self.interest_rate == 11.75
else
self.interest_rate
end
end
根据年份和年龄,它应自动显示兴趣。
我的观看页面:
<h4><%= f.label :periods, class:'required' %>
<%= f.select(:no_of_year, options_for_select([['',''],['1','1'], ['2','2'],['3','3'],['4','4'],['5','5']]))%></h4>
<h4><%= f.label :interest_rate, class:'required' %>
<%= f.text_field :interest_rate, :readonly => true %></h4>
如何以及在何处使用ajax和javascript?
答案 0 :(得分:1)
首先,您最好使用case switch
(在Ruby中):
def calculate_value
case self.age
when >= 75
self.interest_rate = 10 + (0.5 * self.no_of_year) #-> algo to determine interest
when >= 58 && <= 75
self.interest_rate = 10 + (0.5 * self.no_of_year) #-> algo to determine interest
else
self.interest_rate
end
end
-
<强>的Ajax 强>
为了使用Ajax和Javascript,您首先需要endpoint来发送数据。这应该在路线中定义:
#config/routes.rb
get "interest", to: "application#calculate_interest"
这将允许您像这样使用Ajax:
#app/assets/javascripts/application.js
$(".select").on("change", function() { //Binds to your select box "change" event
$.ajax({
url: "/interest", //Sends to your endpoint
data: {"year": $(this).val() }
success: function(data){
//where the response will be processed
$(".textfield").val = data;
}
});
});
上述代码的几点注意事项 -
- 您需要能够选择特定元素 - 我刚刚使用过
.select
等 - 您应该使用id
标记来选择它们 单独- 您的控制器需要处理响应 - 使用
醇>respond_to
块:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def calculate_interest
respond_to do |format|
format.html
format.js
end
end
end
<强>更新强>
如果您要从.on("change"
框的select
事件更新文本框:
$("#test").on("change", function(){
value = $(this).val();
$("#text").val(value);
});
<select id="test">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" id="text" value="testing">