Here is a tutorial that I followed that describes cascading drop down where the next box is loaded via an Ajax call back to the controller.
Dynamic Drop Down
I have a data base as follow:
companies -> id, name contact-> id,name,company_id
now I need a drop down list to choose the company name and then the second drop down displays the name of contacts related to the company that selected.
Any method or solution do you recommend?
Thanks
you have to do this with ajax, so when a user select the company, it loads related
contacts to the contacts drop down..
$(document).ready(function(){
$('#companyDropDown').change(function(){
let companyDropDown = $(this).val();
let lang = $('#lang').val();
axios.get('/getcontacts/' + company_id )
.then(function (response) {
$('#contactDropDown').empty();
$('#contactDropDown').append('<option value=0> select company </option>');
$.each(response.data , function(key , value){
$('#contactDropDown').append('<option value='+value.id+'> '+value.name+'
</option>');
});
})
.catch(function (error) {
console.log(error);
});
});
});
where
companyDropDown is the id of the companies drop down
ContactDropDown is the id of the contacts drop down
@BishoyWagih Where should I use these codes? in the View or Controller?
in the view, you create a seperate js file and include it in your blade temaplte
@BishoyWagih I am very new in Laravel, how can I include a file just for the certain view? this is my view templace
@extends('layouts.app', ['title'=>' Customers '])
@section('content')
@endsection
@section('script')
@endsection
1 - create js file in public directory / js directory
2 - let say file name is companies.js
3 - include it in blade template
@extends('layouts.app', ['title'=>' Customers '])
@section('content')
@endsection
@section('script')
<script src="{{ asset('js/companies.js') }}"></script>
@endsection
@BishoyWagih in the Form Code what is the dropdown ID?
<div class="form-group">
<label>Select company:</label>
{!! Form::select('company_id',[''=>'--- Select Company---']+$companies,null,['class'=>'form-control']) !!}
</div>
it will be generated automatically equivalent to name, so it will be company_id in your case..
I modified the java file as below, it seems the java is not fired by dropdown ID
$(document).ready(function(){
$('#company_id').change(function(){
let company_id = $(this).val();
let lang = $('#lang').val();
axios.get('/customers/' + company_id )
.then(function (response) {
$('#contact_id').empty();
$('#contact_id').append('<option value=0> select company </option>');
$.each(response.data , function(key , value){
$('#contact_id').append('<option value='+value.id+'> '+value.name+'
</option>');
});
})
.catch(function (error) {
console.log(error);
});
});
});
Please or to participate in this conversation.