【问题标题】:jquery Select2 Ajax - How set value (initSelection)jquery Select2 Ajax - 如何设置值(initSelection)
【发布时间】:2013-05-26 06:43:51
【问题描述】:

用户选择的下拉列表项如何设置?

场景:
1. 用户没有在表单中输入所有必需的值
2. 点击发送。
3. 页面被刷新,下拉列表中的值没有被选中。 如何取值?

我有可以为列表检索数据的工作脚本。

$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
    url: "index.php?modul=getusers",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: function (term, page) {
        return {
            q: term,
            page_limit: 10
        };
    },
    results: function (data, page) {
        return { results: data };
    }
},
allowClear: true,
formatSelection: function(data) { 
   return data.text; 
}   
});

ajax 调用中的标准数据: {"text":"示例文本", "id":"1"}

输入:

 

我尝试添加以下代码,但它不起作用

initSelection: function(element, callback) {
    var id=$(element).val();
    if (id!=="") {
       $.ajax("index.php?modul=getusersfriend&q="+id, {
       dataType: "json"
       }).done(function(data) { callback(data); });
    }
},

【问题讨论】:

    标签: jquery-select2


    【解决方案1】:

    确保在 initSelection 的回调中返回格式正确的 JSON 对象。已经解决了here 的讨论。

    但到目前为止看起来不错。您可能希望bind the change 事件的 select 或 form 的 submit 事件在提交表单之前序列化其值。

    您可以将其值存储在您的服务器上(很糟糕),或者只是序列化表单对象并在加载 select2 时获取要传递给 initSelection 的值。

    这里会发生什么:

     var id=$(element).val();
    

    这是一个简单的example 序列化表单。

    PS:真的看不出引导程序与任何事情有什么关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2017-01-04
      • 2013-09-25
      • 2020-07-07
      • 2021-08-30
      相关资源
      最近更新 更多