我有一个vouchers#index.html.erb
,我想要创建一个凭证。我可以成功渲染我的表单但是我遇到的问题是我的先行字段不起作用。
我已设置此按钮以呈现_form:
<div class='row'>
<%= link_to 'New Voucher', new_voucher_path, id: 'new_voucher_btn', class:'btn btn-md btn-primary', remote: true %>
</div>
我的控制器:
def new
@voucher = Voucher.new
@voucher.voucherdetails.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @voucher }
format.js
end
end
New.js.erb
$('#new_voucher_btn').hide().after('<%= j render("form") %>'); //Hide 'New Voucher' button after clicking.
$(".datepicker").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd/mm/yy" }); //add the datepicker
Voucher.js
jQuery(function() {
var customers = jQuery.parseJSON( gon.customer_typeahead )
// This shows the Typeahead when typing
$('.search_cst').typeahead({
source: customers,
display: 'name',
val: 'id'
});
//This sets the value of customer
$('#customer_search').on("change", '#voucher_voucherdetails_attributes_0_s002', function() {
if (this.value != '') {
var current =$('.search_cst').typeahead("getActive");
if (current) {
$('.search_cst').val(current.name);
$('.search_cst_id').val(current.id);
}
} else {
$('.search_cst').val('');
$('.search_cst_id').val('');
}
});
}); //Function
_form.html.erb(仅包括预先输入字段)
<%= f.fields_for :voucherdetails do |vd| %>
<div class='form-group' id='customer_search' data-provide="typeahead">
<%= vd.label :s002, "Customer:" %>
<%= vd.text_field :s002, class:'search_cst form-control' %>
<%= vd.hidden_field :s002, class: 'search_cst_id' %>
</div>
<% end %>
优惠券has_many :voucherdetails
&amp; accepts_nested_attributes_for :voucherdetails, allow_destroy: :true
。
Voucherdetail belongs_to :voucher
我想注意,如果我通过访问url voucher / new来呈现表单,则typeahead有效。我认为问题在于我没有在AJAX调用后正确初始化typeahead。
N.B我正在使用bootstrap3-typeahead.js v 4.0.2 Found Here
我从之前的开发人员那里继承了这个代码库(因此在地方奇怪的命名)。
答案 0 :(得分:0)
回答我自己的问题;我放了
var customers = jQuery.parseJSON( gon.customer_typeahead )
// This shows the Typeahead when typing
$('.search_cst').typeahead({
source: customers,
display: 'name',
val: 'id'
});
//This sets the value of s002
$('#customer_search').on("change",'#voucher_voucherdetails_attributes_0_s002', function() {
if (this.value != '') {
var current =$('.search_cst').typeahead("getActive");
if (current) {
$('.search_cst').val(current.name);
$('.search_cst_id').val(current.id);
}
} else {
$('.search_cst').val('');
$('.search_cst_id').val('');
}
}); //Customer_search on change
进入new.js.erb
&amp;有效。我之前尝试过此操作,但这次认为差异是$('#customer_search').on("change", '#voucher...;
而不是$(document).on("change")...;
通过AJAX调用初始化typeahead。