选择2占位符不在rails app中使用hidden_​​field

时间:2015-05-08 05:00:15

标签: ruby-on-rails jquery-ui jquery-select2 select2-rails

哈姆尔:

 .form-group
            = f.hidden_field :gender, :id => 'select2', :style => "width:100%; height: 40px"

JS:

 $("#select2").select2({
    createSearchChoice: function (term, data) {
      if ($(data).filter(function () {
            return this.text.localeCompare(term) === this.text;
          }).length === 0) {
        return {
          id: term,
          text: term
        };
      }
      console.log('SELECT2', $("#select2").data.text);
    },
    placeholder: "Enter custom gender or select one below",
    multiple: false,
    data: [{
      id: 'male',
      text: 'male'
    }, {
      id: 'female',
      text: 'female'
    }, {
      id: 'custom',
      text: 'custom'
    }]
});

Select2正在做我现在需要的一切,但占位符没有显示在我的视图上。任何帮助,非常感谢。

2 个答案:

答案 0 :(得分:1)

我为此写了一个小咖啡脚本,它可以完成所有正常自动完成的事情以及预先填充的数据

$(document).ready ->
  $('.select2').each (i, e) =>
    select = $(e)
    options =
      placeholder: select.data('placeholder')
      minimumInputLength: 1

    if select.hasClass('ajax') # only add ajax functionality if this class is present
      options.ajax =
        url: select.data('source')
        quietMillis: 100
        dataType: 'json'
        data: (term) ->
          q: term
        results: (data) ->
          results: data.resources
          more: false

      options.dropdownCssClass = "bigdrop"
      options.initSelection = (element, callback) ->
        callback({ text: element.attr('data-value') })
    select.select2(options)

我隐藏的领域就像这样

hidden_field_tag(:search, '', id: 'res_select', class: 'select2 ajax form-control select-overide', style: 'width: 100%;', data: { source: "/products/autocomplete", placeholder: 'Search for a name' }, :value=> params["search"], "data-value" => params['search'])

试试这个它会起作用。

答案 1 :(得分:0)

这是一个很好的答案。我通过预先填充占位符填充的空白初始选项来解决这个问题:

 $('.compare-search').prepend('<option/>').val(function(){return $('[selected]',this).val() ;});