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

设想:
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调用中的标准数据:
{“文本”:“示例文本”,“id”:“1”}

输入:
  <input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid"> 

I tried to add the following code, but it doesn't work

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

请您参考如下方法:

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

但目前看来还不错。您可能想要 bind the change表单的 select 或 submit 事件以在提交表单之前序列化其值。

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

这就是这里会发生的事情:

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

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

PS:不要真的看到 bootstrap 与任何事情有什么关系。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!