javascript - Laravel form validation for returning dropdown values -
when validation fails, want dropdowns have selected values in it.my drop down list populated javascript. validation not validate dropdown box values.
drop down list in 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>
my java script loading values
$(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>'); }); }); }); });
i tried following getting selected values using this tutorial.
<select class="form-control" name="item" id="item"> <option disabled selected>velg...</option> @foreach ($items $item) <option value="{{ $item->name }}" @if (old('item') == $item->name) selected="selected" @endif>{{ $item->name }}</option> @endforeach </select>
ps : when use coding, returns id value, not code in dropdown box.
<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>
but doesn't work. how previosly selected values form?
i believe issue have you're loading in options want selected via ajax after page has loaded.
there many other ways better reuse of code possible i'd push script footer dynamic values straight blade template can access old() in ajax callback.
@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 page has errors use old input check match , select element after ajax request has run @if( count($errors) > 0) if( courses[0].id == {{ old('activityitemsid') }} ) { $('#itemid').val( courses[0].id ); } @else }); }); } // manually populate dropdown if year selected, if select box should change on('click' on('change' $('#year').on('click',function(e){ getitems(e.target.value); }); // if page loaded errors, use year input prepopulate dropdown @if (count($errors) > 0) getitems( {{ old('year') }} ); @endif }); @endpush
this code makes lot of assumptions, you'll have ensure field names correct etc. if i'm using lot of ajax load dynamic form data i'll handle validation on client side laravel validation fallback if disables javascript, way can run post-validation code while retaining current state of dom.
Comments
Post a Comment