Skip to content

Instantly share code, notes, and snippets.

@mmuoDev
Created September 23, 2017 11:08
Show Gist options
  • Save mmuoDev/a63e3352e51b842c9077d92e0a9f8e56 to your computer and use it in GitHub Desktop.
Save mmuoDev/a63e3352e51b842c9077d92e0a9f8e56 to your computer and use it in GitHub Desktop.
Laravel 5 - Dynamically load select box using another select box
For those with Javascript phobia like me, this is how to dynamically load contents into a select box using another select box. This gist uses AJAX and JQuery.
The view
<div class="form-group col-sm-12">
<label class=""> Category</label>
<select name="category" class="form-control category" id="input-category">
<option value=""> --- Please Select ---</option>
@foreach(session('categories') as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
<div class="form-group col-sm-12">
<label class="">Sub Category</label>
<select name="subsidiary" class="form-control" id="subsidiary_id">
<option value=""> --- Please Select ---</option>
</select>
</div>
<-- Include this script in your view -->
<script>
$('.category').on('change', function(e){
//alert('hi');
//console.log(e);
var token = $("input[name='_token']").val();
var category = e.target.value;
//ajax
$.ajax({
url: "<?php echo route('select-subsidiary') ?>",
method: 'POST',
data: {category:category, _token:token},
success: function(data) {
$('#subsidiary_id').empty();
$.each(data, function(index, subCatObj){
$('#subsidiary_id').append('<option value="'+subCatObj.id+'">'+subCatObj.name+'</option>')
});
}
});
});
</script>
Your route file
Route::post('select-subsidiary', 'RequestController@select_subsidiary')->name('select-subsidiary');
Your Controller
public function select_subsidiary(Request $request){
$category = $request->category;
$subsidiary = DB::select("SELECT id, name from (
(SELECT * FROM capital_expenses)
UNION
(SELECT * FROM operating_expenses)
) as t where category_id = '$category'");
//$data = view('ajax-select',compact('states'))->render();
return response()->json($subsidiary);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment