someone?
Aug 21, 2017
4
Level 1
Dependent Dropdown
Hello guys! I'm trying to create a dependent dropdown on country, state and city. It's running, but only after I've changed the country, does it carry the states. I wanted it already loaded the country linked to the user, which is stored in the database, its state and city, when the page loads. And then he can make the switch if he wishes.
My html:
<form method="post" action="">
{{ csrf_field() }}
<label for="Your_location" class="editProfile-Label">Your location</label>
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="form-group">
<select class="form-control" name="countries" id="countries">
@foreach($countries as $countrie)
@if($countrie->name == $data->country)
<option value="{{ $countrie->id }}" selected>{{ $countrie->name }}</option>
@else
<option value="{{ $countrie->id }}">{{ $countrie->name }}</option>
@endif
@endforeach
</select>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
<select class="form-control" id="states" name="states">
</select>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
<select class="form-control" id="cities" name="cities">
</select>
</div>
</div>
</div>
</form>
My JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="countries"]').on('change', function(){
var countryId = $(this).val();
if(countryId) {
$.ajax({
url: '/states/get/'+countryId,
type:"GET",
dataType:"json",
beforeSend: function(){
$('#loader').css("visibility", "visible");
},
success:function(data) {
$('select[class="states_op"]').empty();
$.each(data, function(key, value){
$('select[class="states_op"]').append('<option value="'+ key +'">' + value + '</option>');
});
},
complete: function(){
$('#loader').css("visibility", "hidden");
}
});
} else {
$('select[class="states_op"]').empty();
}
});
});
</script>
My route:
Route::get('states/get/{id}', 'ProfileController@getStates');
Route::get('cities/get/{id}', 'ProfileController@getCities');
My controller:
public function getStates($id) {
$states = States::where("country_id",$id)->pluck("name");
return json_encode($states);
}
public function getCities($id) {
$cities = Cities::where("state_id",$id)->pluck("name");
return json_encode($cities);
}
Ps: Sorry my English
Please or to participate in this conversation.