首页 文章

选择后无法在select2.js中显示占位符

提问于
浏览
1

使用select2.js检索绑定到隐藏输入的远程数据 .

<input type="hidden" id="departmentNameEntry"  style="width:300px"/>

我在初始化中设置了占位符:

$("#departmentNameEntry").select2({
        placeholder: "Search for a department",
        minimumInputLength: 2,
        ajax: {
            url: "Handlers/DeptNameSearch_handler.ashx",
            cache: false,
            dataType: 'json',
            type: 'GET',
            data: function (term, page) {
                return {
                    departmentNameFragment: term // search term entered into querystring for handler
                };
            },
            results: function (data, page) { // parse the results into the format expected by Select2.
                return { results: data };
            }
        },
        formatResult: function (item) {
            return item.text;
        },
        formatSelection: formatDepartmentNames,
        formatNoMatches: function (term) {
            return 'no department name matches your query';
        }
    });

但是只要选择了某个项目,占位符就会变为空白 . 如何将其重置为原始字符串?我已经尝试将init代码放在一个单独的函数中并再次执行它,但没有快乐 . 我见过的其他问题似乎是特定于绑定到SELECT . 我究竟做错了什么?

1 回答

  • 0

    我没有足够接近RTFM .

    formatSelection选项要求您返回一个字符串,然后在select2中显示该字符串以代替占位符文本 . 这是我的功能:

    function formatDepartmentNames(dept) {
        $('#hfDepartmentID').val(dept.id);   // when user has selected from the list, put id in an input
        $('#hfDepartmentName').val(dept.text); // stash the dept name for later
        DepartmentCurrentBossesGet(dept.id, dept.text);  // call another function
        DepartmentBossHistoryGet(dept.id);  // call yet another function
        $('.row4').show();  // show useful data on the page
        return dept.text;   // return the dept name so select2 can display it
    }
    

    希望这有助于某人 .

相关问题