Search code examples
ruby-on-railsjquery-uijquery-select2select2-rails

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.


Solution

  • That's a good answer above. I solved this with less code by prepending a blank initial option, which the placeholder filled in:

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