【问题标题】:Set default selected value in Select2 fetching data from ajax在从 ajax 获取数据的 Select2 中设置默认选定值
【发布时间】:2018-01-24 10:45:02
【问题描述】:

我使用一些输入字段和这个过滤了一个结果列表:

$("#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
                    }
                })
            };
        }
      }
    });

效果很好,但是在提交表单后,我想用我已应用的过滤器填充输入。其他所有输入都可以:

例如:

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

我的页面.php

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

但我不知道如何使用我使用过的搜索自动填充 Select2。例如,如果我写“DEM”,我的 Select2 建议我使用“DEMO CUSTOMER”(ID = 4)。我选择这个,提交表单,重新加载页面后,Select2 idCustomer 仍然为空。 我想使用传递给搜索表单的 id = 4 来初始化它。

我已尝试附加 $("#idCustomer").val(&lt;?php echo $idCustomer; ?&gt;).trigger("change");

但它不起作用。

我使用的是最新的 4.1 版本的插件

【问题讨论】:

    标签: javascript jquery-select2


    【解决方案1】:

    你必须提到自动完成的选择

    //HTML

    //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);
      }
    })
    

    ;

    【讨论】:

      【解决方案2】:

      解决方法:

      <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 完成剩下的工作!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-10
        • 1970-01-01
        • 2013-06-02
        • 2013-11-24
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多