jquery select2 - not working
Asked Answered
K

6

20

I am using select2 plugin(ivaynberg.github.io/select2). I am trying to display a dropdown(select). It is getting all the items in data.php as options. However select2 is meant to be autocomplete plugin and should search for the search term a client input, and display the matching results only. At the moment it is displaying all the items and not getting the search results. Sorry for my language

data.php is echoing out this:

[{
    "id": "1",
    "text": "item1",
    "exercise": "blah text"
  }, {
    "id": "2",
    "text": "item2"
  }
]

The code is:

$(document).ready(function () {
    $('#thisid').select2({
        minimumInputLength: 2,
        ajax: {
            url: "data.php",
            dataType: 'json',
            data: function (term, page) {
                return {
                    q: term
                  };
            },
            results: function (data, page) {
                return {
                    results: data
                };
            }
        }
    });
});

and the input is:

<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />

I want to find a clue, I am quite new to this plugin and have spent a day for looking at examples.

Kendra answered 24/4, 2013 at 10:52 Comment(3)
see ur console for js errorInexcusable
There is no errors on the console.Kendra
it work for me nice....r u include jquery libraryInexcusable
E
32

select2 will not do AJAX if attached to a standard select form control. It MUST be attached to a hidden input control to load via AJAX.

Update: This has been fixed in Select2 4.0. From Pre-Release notes:

Consistency with standard <select> elements for all data adapters, removing the need for hidden <input> elements.

It can also be seen in function in their examples section.

Externalization answered 2/5, 2013 at 18:37 Comment(4)
That is not documented on the site at all. It doesn't even give an example of the html.Saraband
Is there a way to use another method such as $.get to fill the options of the select control? I can't believe they skipped such an important piece of information and that even on ajax (that is quite difficult for first timers)Bowfin
this answer is the correct one. you need to use another component (ex. <div>, <input>, etc) to make select2 ajax, except <select>, no need to be input hidden, because select2 will hidden it for youSerna
For more information refer this link- itfrustration.in/jquery-select2-ajaxDaegal
H
9

I guess user2315153 wants to receive multiple remote values, and incorrectly assigning select2() with ajax call to a <select> element.

The correct way to get remote values, is using a normal <input> element, and if is desired multiple values, inform the "multiple" parameter on method call. Example:

<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
<script>
$('#thisid').select2({
        minimumInputLength: 2,
        multiple: true,
        ajax: {
              ...

The <select> element CAN NOT be used to remote values

UPDATE: As of select2 4.0.0, hidden inputs has deprecated:

https://select2.github.io/announcements-4.0.html#hidden-input

This means: Instead of using an input to attrib select2 plugin, use an SELECT tag.

Pay attention: it's easy to use any format of json from your server. Just use "processResults" to do it.

Example:

<select id='thisid' class='select2-input select2'></select>
<script>
        $("#thisid").select2({
            multiple: true,
            closeOnSelect: true,

            ajax: { 
                url: "myurl",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                      q: params.term,
                      page: params.page
                    };
                  },
                processResults: function (data, page) { //json parse
                    console.log("processing results");
                    //Transform your json here, maybe using $.map jquery method
                    return { 
                       results: yourTransformedJson
                    };
                },
                cache: (maybe)true
            }
        });
</script>
Hoover answered 18/11, 2014 at 20:16 Comment(0)
I
5

I try the code, it works well. I think you not include jquery framework or check the path of js and css.

<!DOCTYPE html>
<html>
<head>
    <link href="select2.css" rel="stylesheet"/>
    <script src="//code.jquery.com/jquery-latest.min.js"></script>
    <script src="select2.min.js"></script>
    <script>
        $(document).ready(function() { 
            $('#thisid').select2({
                minimumInputLength: 2,
        ajax: {
            url: "data.php",
            dataType: 'json',
            data: function (term, page) {
                return {
                    q: term
                  };
            },
            results: function (data, page) {
                return {
                    results: data
                };
            }
        }
    });

        });
    </script>
</head>
<body>
    <input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />

</body>
</html>
Inexcusable answered 24/4, 2013 at 15:49 Comment(3)
Hi, thank you for your answer. however, it does not work - it says :Error: Option 'ajax' is not allowed for Select2 when attached to a <select> element.Kendra
The path is all ok - I am using: bootstrap.css, prettify.css, select2.css,json2.js,jquery-1.7.1.min.js,jquery-ui-1.8.20.custom.min.js,jquery.mousewheel.js prettify.min.js,bootstrap.min.js, select2.min.jsKendra
@Kendra no you did not. You tried to edit THIS post instead.Auriculate
L
1

I think no need to go with hidden input element. You can give a try, get plain html data from ajax call and set it in and then init select2 resetting method. Here's code snippet

HTML

<select id="select" name="select" class="select2">
        <option value="" selected disabled>Please Select Above Field</option>
</select>

Javascript

    $.ajax({
        type: "POST",
        cache:false,
        url: YOUR_AJAX_URL,
        success: function(response)
        {
            $('#select').html(response);
        }
    });
    $('#select').select2("val","");

Ajax Response :

<option value="value">Option Name</option>
.
.
.
<option value="value">Option Name</option>
Ludmilla answered 2/2, 2014 at 5:25 Comment(0)
B
0

After much reading, I decided to change the select2.js itself.

At line 2109 change it to

this.focusser.attr("id", "s2id_"+this.select.context.id);

If your input tag is as so

<select id="fichier">

Hence your input tag that is searching through the list will have an id of s2id_fichier_search

As far as I know, there shouldn't be a conflict and THIS will allow you to have multiple select2 on the same page and run your functions (including .get, .post) through their events eg.

$(function() { 
  $('#s2id_fichier_search').keyup(function() {
    console.log('Be Practical')
  })
}

So this will run like if you were to use

<select id="fichier" onkeyup="console.log('Be Practical')">
Bowfin answered 22/1, 2015 at 14:4 Comment(0)
M
0

In my case, an older version of select2 library was causing the issue, make sure that you include the latest version of js and css in the web page.

Mexico answered 15/12, 2019 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.