使用jquery在rails上的ruby中动态选择

bha*_*ath 3 jquery ruby-on-rails-3

嘿伙计我有一个问题我试图在以下代码中实现动态选择.我有产品和产品有很多批次.只要我选择产品关联批次,就应该显示.表格详情如下.

<div class ="prod"><%= f.association :product, :collection => Product.in_stock %> </div><br/>

<div class ="batch"><%= f.grouped_collection_select :batch_no, Product.in_stock, :store_opening_stocks, :title, :batch_no, :batch_no, :prompt => "Select Batch"%></div>
Run Code Online (Sandbox Code Playgroud)

和表格的jquery如下

jQuery(document).ready(function(){
  var child = jQuery('.batch').html();
  jQuery('.prod').change(function() {
   var parent = jQuery('.prod :selected').text();
   var escaped_parent = parent.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')  
    var options = jQuery(child).filter("optgroup[label='#{escaped_parent}']").html()
     if (options) {
      jQuery('.batch').html(options);
      return jQuery('.batch').parent().show();
    } else {
      jQuery('.batch').empty();
    }
   });
}); 
Run Code Online (Sandbox Code Playgroud)

现在的问题options是返回null.我发现这件事时我发现alert(options)它显示为空.任何人都可以请我正确的方向?有没有其他方法可以完成我的任务.提前致谢 :)

Vik*_*kko 5

jQuery(document).ready(function(){
  var child = jQuery('.batch').html();
  jQuery('.prod').change(function() {
   var parent = jQuery('.prod :selected').text();
   /* var escaped_parent = parent.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1') */  
    var options = jQuery(child).filter("optgroup[label='" + parent + "']").html()
     if (options) {
      jQuery('.batch').html(options);
      return jQuery('.batch').parent().show();
    } else {
      jQuery('.batch').empty();
    }
   });
}); 
Run Code Online (Sandbox Code Playgroud)

这对你有什么魔力吗?

对控制器执行ajax调用并返回选项集可能更清晰,然后使用返回的选项填充批处理.

就像是

var data = {
  product_id: jQuery('.prod :selected').attr("data-id")           
}
jQuery.ajax({
  url: controller/get_batch,
  type: 'GET',
  dataType: 'script',
  data: data
});
Run Code Online (Sandbox Code Playgroud)

你放的是get_batch.js

jQuery('.batch').html(<%= escape_javascript(render :partial => "select_box_for_batch") %>);
Run Code Online (Sandbox Code Playgroud)

代码不完整,您仍需要在产品选择和内容中添加ID,但我认为您会明白这一点.

编辑:我用一个简单的例子建立了一个存储库