George
George

Reputation: 746

Select2 problems with search and initSelection

Select2 code :

$(".js-select").select2( {
    placeholder: "Select Something",

    ajax: {
        // The number of milliseconds to wait for the user to stop typing before issuing the ajax request
        delay: 400,
        url: "<?php echo site_url('main/get_items') ?>",
        dataType: "json",
        cache: "true",

        data: function (params) {
            return {
            q: params.term, // search term
            page: params.page,

            };
        },

        processResults: function (data) {
            return {
                results: $.map(data, function(obj) {
                    return { id: obj.id, text: obj.nume };
                })
            };
        },
    },

    initSelection : function (element, callback) {
         var data = {id: "1", text: "test relation"};
         callback(data);
    },
});

HTML :

<select class="js-select" name="judet" style="width: 100%" required> </select>
  1. First problem : Using initSelection doesn’t work :

Code :

initSelection : function (element, callback) {
    var data = {id: "1", text: "test relation"};
    callback(data);
},

I see the “test relation” text but when i submit i get no value for the id.

  1. Secound problem :

When i try to select 1 item from the dropdown .... Select2 initializes a search ... I need select2 to run search only when users type something for search ...

Webpage : http://www.my-web-projects.com/ajax/main/table -> button ADD ->dropdown Select 1 and select 2

Upvotes: 1

Views: 1282

Answers (2)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41691

First problem : Using initSelection doesn’t work :

This sounds like a bug in Select2, it should attempt to create the <option> elements so the value gets sent. If you can wrap up the bug in a jsbin and report it on GitHub that'd be helpful.

When i try to select 1 item from the dropdown .... Select2 initializes a search ... I need select2 to run search only when users type something for search ...

You should be able to achieve this by using minimumInputLength and setting it to 1. We use this in the AJAX example so the request is only sent off when the user searches.

$element.select2({
  minimumInputLength: 1
});

Upvotes: 1

cyber_rookie
cyber_rookie

Reputation: 665

Change

var data = {id: "1", text: "test relation"};

to

var data = [{id: "1", text: "test relation"}];

EDITED

$(".js-select").select2({/* */}).select2("data", [{"id":"1","text":"test relation"}]);

Upvotes: 0

Related Questions