【发布时间】:2021-05-18 17:20:56
【问题描述】:
i'm trying to show new select input contains (states) options, when user select specific option a (USA) country, and when select another country non (USA) don't show the states select options i want in this案件仍然隐藏。
路线
Route::get('/ajax-form', [AjaxController::class, 'index'])->name('ajax.index');
Route::get('/getState/{id}', [AjaxController::class, 'getState'])->name('ajax.state');
控制器
class AjaxController extends Controller
{
public function index()
{
$countries['data'] = Country::orderby('name')
->select('id', 'name')
->get();
return view('ajax.index', compact('countries'));
}
public function getState($countryId = 0)
{
$states['data'] = State::orderby('name')
->select('id', 'name')
->where('country_id', $countryId)
->get();
return response()->json($states);
}
带脚本的刀片形式:
@extends('layouts.app')
@section('form')
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
@if ($countries['data'] && $countries['data']->count() > 0)
@foreach ($countries['data'] as $country)
<option value="{{ $country->id }}">{{ $country->name }}</option>
@endforeach
@endif
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
@stop
@section('script')
<script type="text/javascript">
$(document).ready(function () {
$('#inputCountry').change(function() {
var id = $(this).val();
// Empty the States dropdown without first
$('#stateShow').show();
$('#inputState').find('option').not(':first').remove();
// ajax request
$.ajax({
url: 'getState/' + id,
type:'get',
dataType: 'json',
success: function(response) {
var len = 0;
if(response['data'] != null) {
len = response['data'].length;
}
if(len > 0) {
// Read data in the state option that related with country
for(var i = 0; i < len; i++) {
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='" + id + "'>" + name + "</option>";
$('#inputState').append(option);
}
}
}
});
});
});
</script>
@stop
上面的脚本在做,当我选择任何国家时,会显示隐藏的(州)选择,我希望它只在我选择(美国)时显示,而不是仍然隐藏
你能帮我吗
【问题讨论】:
标签: javascript php jquery ajax laravel