简体   繁体   English

Select2 jQuery和Rails Ajax表单

[英]Select2 jQuery and Rails ajax form

I'm using the jQuery select2 plugin in my Rails4 app. 我在Rails4应用中使用jQuery select2插件。

The plugin is working for me in forms that are not using ajax. 该插件以不使用ajax的形式为我工作。 But, for ajax forms I don't know how to do it. 但是,对于ajax表单,我不知道该怎么做。

There's a form inside a bootstrap 3 modal, here's how I load the same: bootstrap 3模态中有一个表单,这是我加载它的方式:

<%= link_to t(:new), new_address_path, remote: true, :class => 'btn btn-info'  %>

$('<%= j render "form", title: "#{t(:address)}" %>').modal();

How can I initialise the select2 plugin for the selects inside this form? 如何初始化此表单中的selects的select2插件?

Did I understand it correctly? 我理解正确吗? The form is a modal which is not displayed on the page at first but after some user interactions. 该表单是一种模式,最初不会显示在页面上,而是在一些用户交互之后才会显示。 In that case the on document ready will not find the element to activate select2. 在这种情况下,准备就绪的文档将找不到激活select2的元素。 I would suggest to either use the livequery plugin which observes DOM changes, eg 我建议使用livequery插件来观察DOM的变化,例如

$('form.modal').livequery('.controls select', 
  function(elem){
    $(elem).select2(); 
})

Or you can also put what @Willem suggested into a javascript tag in the html partial of the form modal. 或者,您也可以将@Willem建议的内容放在形式模式的html部分的javascript标记中。

You would do this using javascript : 您可以使用javascript执行此操作:

// On document ready
$(function(){

  $(document).bind('ajaxComplete', function() {
    // Activate select2 after ajax request
    activateJSPlugins();
  });

  activateJSPlugins();
});

function activateJSPlugins()  {
  // Find all dropdowns and initialize select2
  $(".controls select").each(function() {

    // Initialize select2
    $(this).select2();
  });
}

$(".controls select") would be the css selector you apply to find your select2 controls. $(".controls select")将是您用来查找select2控件的css选择器。

EDIT 编辑

/app/assets/javascripts/bootstrap_and_overrides.js /app/assets/javascripts/bootstrap_and_overrides.js

Create a bootstrap_and_overrides.js file. 创建bootstrap_and_overrides.js文件。

/app/assets/javascripts/application.js /app/assets/javascripts/application.js

//= require bootstrap_and_overrides

Then this code will run for all your selec2 inputs 然后,此代码将为您的所有selec2输入运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM