Search code examples
jquery-select2select2-rails

Add fixed item to select2


I am using select2 gem in rails

gem version: 3.5.9.3 select2 version: 3.5.2

Haml view:

= form_tag('cards/search/', method: :get, remote: true, class: 'navbar-form navbar-right') do
  .form-group
    = hidden_field_tag :q, '', id: 'search', class: 'form-control',
      style: 'width: 250px;',
      data: { 'ajax-url' => search_path, placeholder: 'placeholder' }

In coffescript file

$ ->
  $('#search').select2
    minimumInputLength: 1
    ajax:
      dataType: 'json'
      delay: 250
      data: (params) ->
        q: params
      results: (data) ->
        results: data.q

Result

How can I add fixed item to the bottom of options? No matter what I typed in search form.

I tried:

$('#search').append{id: 'test', text: 'test'}

But didn't saw that option.


Solution

  • The two solutions I came up with are:

    1. Create a decorator for select2. Which IMO is quite a cumbersome task since there isn't really any documentation on how to do it that I've found. The best resource I found that helped me was Kvein Brown's reply on this thread:

      https://groups.google.com/forum/#!topic/select2/s4hAHyBrYqc

    2. The other way to do it, and probably the easiest if you're just using one select2 on the page is to listen for select2's open event and then just use jQuery to append a element where you want it.