2016-11-13 74 views
1

当验证失败时,我希望我的下拉列表中有以前选择的值。我的下拉列表是从javascript填充的。验证不会验证此下拉框的值。Laravel表单验证返回下拉值

在我看来下拉列表

<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> 

但它不起作用。如何获得预先选择的表单值?

回答

2

我相信你遇到的问题是,你正在加载的页面加载后,你想通过AJAX选择的选项。

还有很多其他方法可以更好地完成此任务,但要尽可能重复使用您的代码,我只需将脚本从刀片模板直接推入页脚,并使用一些动态值即可访问old()in你的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的加载动态表单数据,我会在客户端上处理验证如果某人禁用Javascript,则可以使用Laravel验证作为后备,这样,您可以在保留DOM的当前状态的同时运行后验证代码。