当验证失败时,我希望我的下拉列表中包含之前选择的值。我的下拉列表是从 javascript 填充的。验证不验证此下拉框值。
我 View 中的下拉列表
<div class="form-group">
<label align="right" for="ItemID" class="control-label col-xs-2">Item :</label>
<select class="col-md-5 input-sm" name="itemID" id="ItemID" >
<option> </option>
</select>
</div>
我用于加载值的 java 脚本
$(document).ready(function(){
$('#Year').on('click',function(e){
var year= e.target.value;
$.getJSON('/xxxxx/xxx?year=' + year, function(data){
$('#ItemID').empty();
$.each(data,function(index, courses){
$('#ItemID').append('<option value="'+courses[0].ID+'">'+courses[0].Code+'</option>');
});
});
});
});
我尝试使用 this tutorial 获取先前选择的值.
<select class="form-control" name="item" id="item">
<option disabled selected>Velg...</option>
@foreach ($items as $item)
<option value="{{ $item->name }}" @if (old('item') == $item->name) selected="selected" @endif>{{ $item->name }}</option>
@endforeach
</select>
PS : 当我使用这种编码时,它返回的是 ID 值,而不是下拉框中的代码。
<div class="form-group">
<label align="right" for="ActivityItemsID" class="control-label col-xs-2">Activity : </label>
<select class="col-md-5 input-sm" name="ActivityItemsID" id="ActivityItemsID" >
<option value="{{Input::old('ActivityItemsID')}}" > {{Input::old('ActivityItemsID')}} </option>
<option value=" "> </option>
</select>
</div>
但它不起作用。如何获取之前为表单选择的值?
最佳答案
我认为您遇到的问题是您在页面加载后加载了要通过 AJAX 选择的选项。
还有许多其他方法可以更好地做到这一点,但为了尽可能多地重用代码,我只是将脚本推送到页脚,其中包含一些直接来自 Blade 模板的动态值,这样您就可以访问 old() ajax 回调。
@push('scripts')
$(document).ready(function(){
function getItems(year) {
$.getJSON('/xxxxx/xxx?year=' + year, function(data){
$('#ItemID').empty();
$.each(data,function(index, courses){
$('<option value="'+courses[0].ID+'">'+courses[0].Code+'</option>').appendTo('#ItemID');
// If the page has errors we use the old input to check for a match and select the element after the ajax request has run
@if( count($errors) > 0)
if( courses[0].ID == {{ old('ActivityItemsID') }} ) {
$('#ItemID').val( courses[0].ID );
}
@else
});
});
}
// Manually populate the dropdown if a year is selected, if this is a select box you should change on('click' to on('change'
$('#Year').on('click',function(e){
getItems(e.target.value);
});
// If the page loaded with errors, use the year from the input to prepopulate the dropdown
@if (count($errors) > 0)
getItems( {{ old('year') }} );
@endif
});
@endpush
这段代码做了很多假设,你必须确保字段名称是正确的等等。一般来说,如果我使用大量的 ajax 来加载动态表单数据,我会在客户端使用 Laravel 验证来处理验证就像有人禁用 Javascript 时的回退一样,这样您就可以运行验证后代码,同时保留 DOM 的当前状态。
关于javascript - 用于返回下拉值的 Laravel 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40570811/