简体   繁体   English

在Select2中设置默认选定值,以从Ajax获取数据

[英]Set default selected value in Select2 fetching data from ajax

I filter a list of result using some input fields and this one: 我使用一些输入字段和以下内容过滤结果列表:

$("#idCustomer").select2({
      allowClear: true,
      placeholder: "Filter",
      ajax: {
        url: 'ajax/search_customers.php',
        dataType: 'json',
        type: "GET",
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.Name,
                        id: item.ID
                    }
                })
            };
        }
      }
    });

It works great, but after submit the form, I'd like to fill the inputs with filter i've been applied. 效果很好,但是提交表单后,我想用已经应用的过滤器填充输入。 Ok for all others inputs: 可以接受其他所有输入:

For example: 例如:

<input id="minRange" name="minRange" value="<?php echo $minRange; ?>">

My page.php 我的page.php

if ( isset($_POST) ) {
    $minRange = $_POST['minRange'];
    $idCustomer = $_POST['idCustomer'];
    ...
}

But i don't know how to autofill Select2 with the search i've used. 但是我不知道如何用我使用的搜索自动填充Select2。 For example if i write "DEM" my Select2 suggest me "DEMO CUSTOMER" (with ID = 4). 例如,如果我写“ DEM”,我的Select2建议我“ DEMO CUSTOMER”(ID = 4)。 I select this, submit the form, and after reload the page, Select2 idCustomer still empty. 我选择它,提交表单,然后在重新加载页面后,Select2 idCustomer仍然为空。 I'd like to inizialize it using id = 4 passed to the form for the search. 我想使用传递给表单进行搜索的id = 4将其初始化。

I've tried to append $("#idCustomer").val(<?php echo $idCustomer; ?>).trigger("change"); 我试图追加$("#idCustomer").val(<?php echo $idCustomer; ?>).trigger("change");

but it doesn't work. 但这不起作用。

I'm using latest 4.1 version of the plugin 我正在使用最新的4.1版本的插件

you have to mention select for autocomplete 您必须提及选择自动完成功能

//HTML // HTML

//JS // JS

$("#idCustomer").select2({
  allowClear: true,
  placeholder: "Filter",
  ajax: {
    url: 'ajax/search_customers.php',
    dataType: 'json',
    type: "GET",
    processResults: function (data) {
        return {
            results: $.map(data, function (item) {
                return {
                    text: item.Name,
                    id: item.ID
                }
            })
        };
    }
  },
  minLength: 2,
  select: function(event, ui) {

    var Name = ui.item.Name;
    $("#minRange").val(Name);
  }
})

; ;

Solved with: 解决:

<select id="idCustomer" name="idCustomer" class="form-control">
                    <?php if ( $idCustomer != "" ) { ?><option value="<?php echo $idCustomer; ?>"><?php echo get_info_by_id($idCustomer)['Name']; ?></option><?php } ?>
</select>

Select2 does the rest! Select2完成其余工作!

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

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