Mar*_*son 9 ajax laravel jquery-select2 laravel-5
我在我的webapplication中使用Select2.我用Ajax加载我的Select2框.验证失败时,除Select2框外,所有输入都按照之前的方式填充.如何在表单验证失败后恢复旧值?我的赌注是使用Request::old('x')
,但这会插入值(在我的情况下是用户ID)而不是所选文本.因此,例如文本John
将变为27
选择框.我怎样才能收回文字?
<select id="customer" name="customer" class="searchselect searchselectstyle">
</select>
Run Code Online (Sandbox Code Playgroud)
js:
token = '{{csrf_token()}}';
$(".searchselect").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
return {
term: params.term,
'_token': token,
'data' : function(){
var result = [];
var i = 1;
$('.searchselect').each(function(){
result[i] = $(this).val();
i++;
});
return result;
}
};
},
url: function() {
var type = $(this).attr('id');
return '/get' + type;
},
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
Run Code Online (Sandbox Code Playgroud)
编辑
到目前为止我发现的唯一(脏)解决方案如下:
<select id="customer" name="customer" class="searchselect searchselectstyle">
@if(Request::old('customer') != NULL)
<option value="{{Request::old('customer')}}">{{$customers->where('id', intval(Request::old('customer')))->first()->name}}</option>
@endif
</select>
Run Code Online (Sandbox Code Playgroud)
$customers
是一个所有客户的列表,所以这意味着对于每个Select2框,我需要查询一个大的项目列表,以使其工作.如果我们在每个Select2框中讨论数千行,这将是非常低效的.
我想必须有一个更好的解决方案.谁能帮我?
也许你可以尝试(一旦ajax调用结束):
var oldCustomer = $('#customer > option[value={{ Request::old('customer') }}]');
if (oldCustomer.length > 0) {
oldCustomer.attr('selected', 'selected');
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3871 次 |
最近记录: |