jquery-select2 – 使用ajax选择2个默认选项

前端之家收集整理的这篇文章主要介绍了jquery-select2 – 使用ajax选择2个默认选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有下一个 HTML结构
<select class="change_item_dropdown_ajax form-control" id="item_id" name="item_id" onchange="updateData(this,this.value,16)" >
<optgroup label="System Data">
  <option value="17">Test</option>
  <option selected="selected" value="18">System</option>
</optgroup>
</select>

使用Javascript

$(".change_item_dropdown_ajax").select2({
        ajax: {
            url: "get_user_items",dataType: 'json',delay: 250,theme: "classic",data: function (params) {
                return {
                    q: { name_contains: params.term } // search term
                };
            },processResults: function (data) {
                return {
                    results: data
                };
            },cache: true
        },allowClear: true,placeholder: '--- Please select item ---',minimumInputLength: 1
    });

我希望客户能够看到一些带有< optgroup label =“System Data”>项的默认系统选项,还可以添加通过自己的项目进行搜索ajax查询功能.

但是在绑定select2之后它没有显示< optgroup label =“System Data”> …< / optgroup>,

select2选项为空,只显示提示“请输入1个或多个字符”.

感谢,是否有可能做到这一点甚至不清楚.

UPD
select2 removes default options when using ajax有关

使用ajax适配器时,Select-2会删除选项.

UPD2 github issue https://github.com/select2/select2/issues/3828

解决方法

如果你想要一个< optgroup>无论客户端搜索什么内容,它始终可见,而在另一个< optgroup>中,您希望查看搜索结果,请尝试以下操作:

在服务器端脚本中,您正在处理客户端键入的搜索查询,您应该返回一个json_encoded数组,其中包含您要在选择框中显示的项目.而不是这样,尝试做这样的事情:

**在问题评论中根据您的要求修改代码**

$q=$_REQUEST['q']; //the query string passed,note,that if you have minimumInputLength set,until that inputLength is reached,this part of the code won't run,so if you require the minimumInputLength,you should play with the templateResult option of select2
if (empty($q)) {
   $results=array();
   $result[0]=array(); //an optgroup to display when no query was sent
   $result[0]['text']='System Data';
   $result[0]['children']=array();
   // populate your first optgroup here,using the format which you are sending to select2.
} else {    
   $result[0]=array(); //an optgroup for results for the users searches
   $result[0]['text']='User results';
   $result[0]['children']=array();
   //populate the children array with the search related results
}

// json_encode the $result array,and return it

我正在使用一个simmilar代码,它在我身边发挥作用,但有可能在它工作之前必须设置其他一些东西(几个月前我写了代码,我记得我有一个相当难的时间搞清楚了,如果这种方法不起作用,请通知我,我会查看我的代码,看看我是如何做到的.

原文链接:https://www.f2er.com/jquery/178395.html

猜你在找的jQuery相关文章