i was looking for a dynamic dependent dropdown selectbox, so i found a video i copy the code line by line from him but my code is not working idk why.
here is my MainController.php
<?php
namespace App\Http\Controllers;
use App\State;
use App\Country;
use Illuminate\Http\Request;
class MainController extends Controller
{
public function index()
{
$countries = Country::all();
return view('index', compact('countries'));
}
public function getStates($id)
{
$states = State::where('country_id', $id)->pluck('name', 'id');
return json_encode($states);
}
}
My routes:
Route::get('/', 'MainController@index')->name('index');
Route::get('/getStates/{id}', 'MainController@getStates')->name('getStates');
index.blade.php:
<div class="panel panel-primary">
<div class="panel-heading">
<h2 class="text-center">Multi Dropdown</h2>
</div>
<div class="panel-body">
<div class="col-md-3">
<select name="country" id="country" class="form-control">
<option value="" selected="false">Country</option>
@foreach ($countries as $country)
<option value="{{$country->id}}">{{$country->name}}</option>
@endforeach
</select>
</div>
<div class="col-md-6 mt-3">
<select name="state" id="state" class="form-control">
<option value="" selected="false">State</option>
</select>
</div>
</div>
<div class="col-md-3 mt-3">
<button class="btn btn-primary rounded" type="submit" name="search">Search <i
class="fa fa-search"></i></button>
</div>
</div>
Jquery code:
<script type="text/javascript">
jQuery(document).ready(function (){
jQuery('select[name="country"]').on('change',function(){
var countryID = jQuery(this).val();
if (countryID) {
JQuery.ajax({
url:'/getStates/'+countryID,
type: 'GET',
dataType:'json',
success:function(data){
jQuery('select[name="state"]').empty();
jQuery.each(data,function(key,value){
$('select[name="state"]').append('<option value="'+ key +'">'+value+'</option>');
});
}
});
}
else{
$('select[name="state"]').empty();
}
});
});
</script>
it is not working :(