usearch
usearch

Reputation: 75

jquery select2 does not work for me

I am trying to create simple popup which will contains ajax loaded select2 element... but when ever I put it in,,, select2 is not visible inside of colorbox...

var wrapper = $("<div/>");
var a = $('<input type="hidden" id="e6" style="width:200px" value="16340"/>');
a.select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: {
        url: "ajax.php",
        dataType: 'json',
        data: function(term, page) {
            return {
                city: term,
                type: 'name'
            };
        },
        results: function(data, page) {
            return {
                results: data
            };
        }
    },
    initSelection: function(element, callback) {},
});
wrapper.append(a);
$.colorbox({
    rel: 'group2',
    html: wrapper,
    width: '40%',
    height: '40%'
});

Upvotes: 1

Views: 620

Answers (1)

manishie
manishie

Reputation: 5322

This is because you are running select2 on the a element before the element is actually added to the DOM. You need to add it first, then run select2 once it's in the DOM.

You can do that with a callback that runs when the colorbox has completed loading:

var wrapper = $("<div/>");
var a = $('<input type="hidden" id="e6" style="width:200px" value="16340"/>');

wrapper.append(a);

$.colorbox({
  rel: 'group2',
  html: wrapper,
  width: '40%',
  height: '40%'
});

$(document).bind('cbox_complete', function() {
  $('a').select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: {
      url: "ajax.php",
      dataType: 'json',
      data: function(term, page) {
        return {
          city: term,
          type: 'name'
        };
      },
      results: function(data, page) {
        return {
          results: data
        };
      }
    },
    initSelection: function(element, callback) {

    },

  });
});

Upvotes: 1

Related Questions