php 根据第一个下拉选择显示第二个下拉列表(键,值)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 根据第一个下拉选择显示第二个下拉列表(键,值)相关的知识,希望对你有一定的参考价值。
DB setup
table: investment_memos_options
id | investment_memos_fund_id | name | label
table: investment_memos_funds
id | name | fund
<?php
// ROUTE
Route::get('/files/investment-memos/getoptions/{id}','InvestmentMemosController@getOptions')->name('investment.option') ; // ajax()
// MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
class InvestmentMemosOption extends Model
{
protected $fillable = [
'investment_memos_fund_id',
'name',
'label'
] ;
public function investmentMemoFund() {
return $this->belongsTo('App\InvestmentMemosFund', 'investment_memos_fund_id') ;
}
}
// CONTROLLER:
namespace App\Http\Controllers\Admin;
use Session;
use App\InvestmentMemo;
use App\InvestmentMemosFund;
use App\InvestmentMemosOption;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class InvestmentMemosController extends Controller
{
public function index() {
$funds = InvestmentMemosFund::all() ;
return view('admin.investment-memos.index')->with('funds', $funds) ;
}
public function getOptions( $fund_id ) {
// InvestmentMemosOption table needs to contain investment_memos_fund_id as foreign key
$options = InvestmentMemosOption::where('investment_memos_fund_id', $fund_id )->pluck('label','name');
return json_encode($options);
}
}
// VIEW + AJAX
<form >
<div class="form-group">
<select class="form-control" name="investment_memos_fund" id="fund_dropdown">
<option selected disabled>-- Choose Fund --</option>
@foreach( $funds as $fund )
<option value="{{ $fund->id }}">{{ $fund->name }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<select class="form-control" name="investment_memos_options" id="option_dropdown">
</select>
</div>
</form>
<script>
$('#fund_dropdown').on('change', function() {
$('#option_dropdown').empty();
var id = $('#fund_dropdown').val();
$('#option_dropdown').html('<option selected="selected" value="">-- Choose Property --</option>');
//var url = url + '/getOption/'+id;
$.ajax({
url: "http://adler.test/admin/files/investment-memos/getoptions/" + id,
type: "GET",
dataType: "json",
// can use 'id', 'name' or whatever value we are trying to display in the select input
// this needs to be specified in the controller too, the key/value column fields
success:function(data) {
console.log(data);
$('#option_dropdown').html('<option selected="selected" value="">Select Option</option>');
$.each(data, function(label, name) {
console.log('key: ' + label + ' , value: ' + name ) ;
$('#option_dropdown').append('<option value="' + label + '">' + name + '</option>');
});
}
});
});
</script>
以上是关于php 根据第一个下拉选择显示第二个下拉列表(键,值)的主要内容,如果未能解决你的问题,请参考以下文章
如何使用Javascript根据先前的下拉值显示第二个下拉列表