2016-11-13 107 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的當前狀態的同時運行後驗證代碼。