AJAX filled Select2 not clickable
Asked Answered
F

2

8

I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?

Video:

enter image description here

My code:

This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.

<div class="form-group">
    <label for="select"> Partner: </label>
    <select id="select" name="select" class="searchselect searchselectstyle">
        @foreach($partners as $i => $partner)
            <option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
        @endforeach
    </select>
</div>

Here Is the second select box, with the error.

<div class="form-group" >
    <label for="select2"> Hoofdgebruiker: </label>
    <select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">

    </select>
</div>


<script type="text/javascript">
$(document).ready(function(){
    var url = '/json/getusers';
    var $post = {};
    $post.id = $("select").val();

    $.ajax({
        type: "POST",
        dataType: "json",
        url: url,
        data: $post,
        cache: false
    }).done(function(data){
                $('#select2')
                        .find('option')
                        .remove()
                        .end();

                $.each(data, function(i, value) {
                    console.log(data);
                    $('#select2').append($('<option>').text(value.text).attr('value', value.id));
                });
            }
    );
});

-

public function getusers(){
    if(!isset($_POST['term'])){
        $users = User::where('partner_id', $_POST['id'])->get();
    }else{
        $wildcard = '%'.$_POST['term'].'%';
        $users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE',  $wildcard)->get();
    }

    $array = array();

    foreach($users as $i => $user){
        $array[$i] = array("id" => $user->id, "text" => $user->email);
    }
    return response()->json($array);
}
Fitly answered 21/2, 2016 at 19:2 Comment(9)
Have you tried appending a blank option (<option></option>) before the $.each function?Alford
@ArmanOzak That gives me a small empty option, like here: gyazo.com/17a79875dd28a43cac148f576c5eb659Fitly
OK. Could you also add a data-placeholder="Anything you like here" on your <select> tag? By the way, when you do that, you should add a blank option to your PHP too.Alford
@ArmanOzak same problem: bit.ly/20Oi3WqFitly
One last idea: Could you please try putting $('#select2').select2('destroy'); before creating the new options and $('#select2').select2(); after creating them? If that also doesn't work, I am out of ideas, I promise. (:Alford
@ArmanOzak Did not work unfortunately, thanks for your help though :)Fitly
re you sure that the backend is receiving the right data?Swollen
Are you loading the ajax info prior to the Select2 being initiated?Exciseman
@DanL I got it fixed a long time ago as shown in the post, but still thanks for trying to help ;-)Fitly
F
1

I found a solution, which is the following:

<script type="text/javascript">
    $(document).ready(function() {
        $(".searchselect").select2();

        search();
        $("#select").change(function(){
            search();
        });
    });

    function search(){
        var $post = {};
        $post.id = $("#select").val();
        $("#select2").select2({
            ajax: {
                dataType: "json",
                type: "POST",
                data: function (params) {
                    var query = {
                        term: params.term,
                        id: $post.id
                    };
                    return query;
                },
                url: '/json/getusers',
                cache: false,
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });
    }
</script>

Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

Fitly answered 29/2, 2016 at 18:34 Comment(0)
R
8

Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".

{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}

not like that

{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
Rahn answered 30/3, 2018 at 12:26 Comment(1)
very thank you brother! this is a solution! the parameter really need be 'id', not another name.Adolescent
F
1

I found a solution, which is the following:

<script type="text/javascript">
    $(document).ready(function() {
        $(".searchselect").select2();

        search();
        $("#select").change(function(){
            search();
        });
    });

    function search(){
        var $post = {};
        $post.id = $("#select").val();
        $("#select2").select2({
            ajax: {
                dataType: "json",
                type: "POST",
                data: function (params) {
                    var query = {
                        term: params.term,
                        id: $post.id
                    };
                    return query;
                },
                url: '/json/getusers',
                cache: false,
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });
    }
</script>

Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

Fitly answered 29/2, 2016 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.