简体   繁体   English

使用 Ajax 自动完成在 select2 上选择的选项

[英]Selected option on select2 using Ajax Autocomplete

I'm trying to select a value into a select box using Select2 and Ajax autocomplete with Laravel and Blade.我正在尝试使用 Select2 和 Ajax 自动完成 select 框中的 select 值和 Blade。 I have the problem only on edit-mode (when I already have a value on DB) and it works without problme in insert-mode.我只在编辑模式下遇到问题(当我已经在 DB 上有一个值时)并且它在插入模式下没有问题。 Here my html code where the select is empty:这是我的 html 代码,其中 select 为空:

<select class="form-control" id="city-name" name="city" style="width: 100%">
    {{ isset($indirizzi->city_id) ? "<option value=\"". $indirizzi->city->id ."\" selected>".$indirizzi->city->name."</option>" : "" }}
</select>

Here my javascript code where I get value from DB and create a new option value:这是我的 javascript 代码,我从 DB 获取值并创建一个新的选项值:

<script>
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    @if(isset($indirizzi))
        var newOption = new Option('{{ $indirizzi->city->name }}', '{{ $indirizzi->city->id }}', true, true);
        var txtOption = '<option value="{{ $indirizzi->city->id }}" selected>{{ $indirizzi->city->name }}</option>';
        $('#city-name').append(txtOption).val('{{ $indirizzi->city->id }}');
        $('#city-name').select2().trigger('change');
    @endif

    $().ready(function () {
        $("#city-name").select2({
            ajax: {
                url: "{{ route("ajaxFindCity") }}",
                dataType: 'json',
                delay: 250,
                type: "POST",
                data: function (params) {
                    return {
                        _token: CSRF_TOKEN,
                        city: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                error: function (data) {
                    showException(data);
                },
                cache: true
            },
            minimumInputLength: 3,
            templateSelection: function (data) {
                return data.city;
            }
        });
    });
</script>

But on loadind the page I can see the selected value into my selectbox but doesn't work the search of a new value...但是在加载页面时,我可以在我的选择框中看到所选值,但无法搜索新值...

This is the code of function into route("ajaxFindCity") that works if I'm not in edit view:如果我不在编辑视图中,这是 function 到 route("ajaxFindCity") 的代码:

public function ajaxFind(Request $request)
{
    // Recupero la città da ricercare
    $city = $request->get("city");
    // Recupero le città che rientrano nella mia ricerca
    $cities = City::with('province')->where('cities.name', 'like', $city . '%')->get();
    $result = [];
    foreach ($cities as $city) {
        $result[] = [
            "id" => $city->id,
            "text" => $city->name . " (" . $city->province->code . ")",
            "city" => $city->name,
            "province" => $city->province->code
        ];
    }
    return response()->json($result);
}

As seen in the documention for default value ( https://select2.org/data-sources/ajax#default-pre-selected-values ) You need to remove the extra code:如默认值( https://select2.org/data-sources/ajax#default-pre-selected-values )文档中所见,您需要删除额外的代码:

@if(isset($indirizzi)
  ...
@endif

And replace your select by:并将您的 select 替换为:

<select class="form-control" id="city-name" name="city" style="width: 100%">
@if($indirizzi)
   <option value="{{ $indirizzi->city_id }}" selected="selected"> {{ $indirizzi->city->name }}</option>
@endif
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM