I have an dropdown that I want it to make dynamic. In my example, a service has many categories and a categories belongs to a specific service. When a dropdown service is selected. It will display only all the categories that belongs to that service in the second dropdown.
So here's what I have done so far.
In my fields.blade.php
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('client_id', 'Client Name:') !!}
{!! Form::select('client_id', $client, null, ['class' => 'form-control','required'])!!}
</div>
<!-- Service Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('service_id', 'Service:') !!}
{!! Form::select('service_id', $services, null, ['class' => 'form-control','required'])!!}
</div>
In my JS script
$(function() {
$('#service_id').change(function() {
var url = '' + '/service/' + $(this).val() + '/categories/';
$.get(url, function(data) {
var select = $('form select[name= category_id]');
select.empty();
$.each(data,function(key, value) {
select.append('<option value=' + value.id + '>' + value.name + '</option>');
});
});
});
});
In my routes web.php
Route::group(['prefix' => 'encoder','namespace' => 'Encoder'], function () {
Route::get('service/{service}/categories', 'ServiceController@getCategories');
});
In my ServieController.php
public function getCategories($idService)
{
if(!is_numeric($idService)) abort(404);
$service = Service::findOrFail($idService);
return $service->categories->pluck('name', 'id');
}
I think I am already fetching the right data because when a specific service has 2 categories. It returns me also 2, but the value is undefined in the dropdown.
Appreciate if someone could help. Thanks in advance.
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2GX7UFD
via IFTTT
Aucun commentaire:
Enregistrer un commentaire