我正在使用Laravel并使用ajax进行make dropdown依赖。但是,该下拉列表无法显示引用数据库的所选数据。 怎么做?应该使用ajax还是其他方式?
这是我的下拉部分的编辑表单代码:
<!-- dropdown using ajax -->
<div class="form-group">
<label for="title">Pilih Produk :</label>
<select name="id_produk" class="form-control" style="width:350px">
<option value="">- Produk -</option>
@foreach ($produks as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
</select>
</div>
@if ($errors -> any())
<div class="form-group {{ $errors -> has('id_item') ? 'has-error' : 'has-success' }}">
@else
<div class="form-group">
@endif
<label for="title">Pilih Item :</label>
<select name="id_item" class="form-control" style="width:350px">
<option value="">- Item -</option>
</select>
@if ($errors -> has('id_item'))
<span class="help-block">{{ $errors -> first('id_item') }}</span>
@endif
</div>
<script src="{{ asset('http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="id_produk"]').on('change', function() {
var produkid = $(this).val();
if(produkid) {
$.ajax({
url: 'edit/ajax/'+produkid,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="id_item"]').empty();
$.each(data, function(key, value) {
$('select[name="id_item"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="id_item"]').empty();
}
});
});
</script>
<!-- end -->
答案 0 :(得分:0)
在编辑页面上时,需要为选项中的选定值添加条件。
<select name="id_produk" class="form-control" style="width:350px">
<option value="">- Produk -</option>
@foreach ($produks as $key => $value)
<option value="{{ $key }}" selected="{{$key == $editData->id_produk ? 'selelcted' : ''}}">{{ $value }}</option> // Here $editData is the collection by which you add the email and other option in the page
@endforeach
</select>