I am trying to get dynamic drop downs working with Laravel and Select2. There are two drop downs; one for companies i.e. "company2" and one for locations that belong to that company i.e. "location2".
For the life of me, I cannot figure out how to make the "company2" drop down fire a event to read that companies locations, if it is changed! What am I doing wrong in the javascript section of this code! (everything else works)
Route
Route::controller('api', 'ApiController');
Controller (ApiController)
public function getLocations($companyId)
{
return Location::where('company_id', $companyId)->lists('id', 'name');
}
Example output from address "api/locations/7"
{"Yellowstone":"8"}
View (form open/close section omitted)
{!! Form::select('company_id', $companies, null, ['class' => 'company2 form-control']) !!}
{!! Form::select('location_id', $locations, null, ['class' => 'location2 form-control']) !!}
View (Javascript)
<script type="text/javascript">
$(document).ready(function() {
$(".company2").select2();
$(".location2").select2();
});
$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
url:"../api/locations/" + $company2.val(),
type:'GET',
success:function(data) {
var $location2 = $(".location2");
$location2.empty();
$.each(data, function(value, key) {
$location2.append($("<option></option>").attr("value", value).text(key));
});
$location2.select2();
}
});
}).trigger('change');
</script>
The view is passed a list of active companies when initialized i.e.
$companies = Company::lists('trading_name', 'id');
$('.company2').select2().on('change'
... event/listener into the document ready function - perhaps give it a shot – Kan$.ajax
function a third argumentsuccess: function(data) { console.log(data)}
and you'll see your data when the event is triggered - this is where you should be doing the logic to add the location values to the drop down. I'll try to throw together an example – Kan