使用jQuery在Ruby on Rails中动态选择 [英] Dynamic select in ruby on rails using jquery

查看:84
本文介绍了使用jQuery在Ruby on Rails中动态选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我在以下代码中尝试实现动态选择时遇到了问题.我有产品,产品有很多批号.一旦我选择产品关联的批次",就应该显示否".表单详细信息如下.

Hey Guys i have a Problem i trying to implement dynamic select on the in the following code. I have product and product has many batch nos. as soon as i select Product associated Batch no should be displayed. Form details are as follows.

<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>

jquery的形式如下

and jquery for the form is as follows

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();
    }
   });
}); 

现在问题是options返回空值.我在执行alert(options)时发现了此错误,它显示为null.谁能请我向正确的方向前进?还有什么其他方法可以实现我的任务.在此先感谢:)

Now the problem is options is returning null. this i found out when i did alert(options) it is showing null. Can anyone please poitn me to right direction?? is there any other way i can achieve my task. Thanks in advance :)

推荐答案

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();
    }
   });
}); 

这对您有什么魔力吗?

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

It might be cleaner to do a ajax call to your controller and return the set of options, then fill the batch with the options returned.

类似

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

将get_batch.js放在其中

with a get_batch.js where you put

jQuery('.batch').html(<%= escape_javascript(render :partial => "select_box_for_batch") %>);

代码不完整,您仍然需要在产品选择和填充中添加一个ID,但我想您会明白的.

Code is not complete, you still need to add an ID to the product select and stuff, but I think you'll get the idea.

我用一个简单的示例制作了存储库

edit: I made a repository with a simple example

这篇关于使用jQuery在Ruby on Rails中动态选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆