Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 placeholder not working in rails app with hidden_field

Haml:

 .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 is doing everything I need now, but the placeholder is not showing on my view. Any help, much appreciated.

like image 986
NoobSter Avatar asked Nov 27 '25 16:11

NoobSter


1 Answers

I have written a small coffee script for this which does all the things normal auto-complete thing plus pre-filled data

$(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)

And my hidden field is like this

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'])

Try this it will work.

like image 131
Sagar.Patil Avatar answered Nov 29 '25 04:11

Sagar.Patil