Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An event is interfering with Select2 plugin's ajax-retrieved results

I'm using Igor Vaynberg's Select2 jQuery plugin with the Infinite Scroll with Remote Data option to make an autocomplete search box for my website. The AJAX is working great and the results are showing up, but they are unselectable -- the change event is never fired and when you click on a result, nothing happens.

There are also no errors showing up in the Chrome console, so I think it's not a syntax error, rather the plugin is mistaking it for a disabled select box. EDIT: having tried a separate on-click event for the result list which never got fired either, I'm now pretty sure there's something interfering with the events.

Here's my code currently,

// Search
$("#site-search").select2({
    placeholder: "Search posts",
    minimumInputLength: 3,
    ajax: {
        url: "http://localhost/mysite/search",
        dataType: 'json',
        quietMillis: 500,
        data: function (term, page) {
            return {
                q: term,
                page_limit: 10,
                page: page // page number
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.length; // whether or not there are more results available

            // return the value of more to tell if more results can be loaded
            return {results: data, more: more};
        }
    },
    formatResult: function(post) {
        // return html markup for individual result item
        markup = '<img src="'+post.image+'" style="width:40%;float:left;margin-right:5px">';
        markup += '<p>'+post.title+'</p>';
        markup += '<div class="clearfix"></div>';
        return markup;
    },
    formatSelection: function(post) {
        // This shows up in the select box
        return post.title;
    },
    dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
}).on('change', function(e) {
    try {
        var slug = e.val.slug;
        window.location.href = "http://localhost/mysite/posts/"+slug;
    } catch(error) {
        console.log('Selected search result is invalid: ');
    }
});

The select box itself is just an input with type: hidden

<input type="hidden" class="bigdrop" id="site-search" style="width:100%;height:auto">
like image 554
BenjaminRH Avatar asked Jan 07 '13 09:01

BenjaminRH


1 Answers

Your problem seems like, your result data doesn't have a property named "id". Select2 plugins wants an id field on data and if it has not, it makes option "unselectable". You may give an id function to override this behavior:

$("#site-search").select2({
   id: function(obj) {
      return obj.slug; // use slug field for id
   },
   ...
like image 126
Murat Çorlu Avatar answered Oct 02 '22 18:10

Murat Çorlu