![](/img/trans.png)
[英]Javascript SELECT BOX options dependent on other SELECT BOX option selected
[英]dynamic select2 options depending on other select's selected option
我有以下 select
<select class="form-control" id="from-location" name="from-location">
<option value="1">Inventory 1</option>
<option value="2">Inventory 2</option>
<option value="3">Inventory 3</option>
</select>
每個庫存都有產品(顯然不同,但相同的產品可以在多個庫存中)。 我在同一頁面上也有一個 select2(可搜索選擇),我想根據我在第一個 select 中選擇的選項將產品呈現為選項。示例:如果我 select Inventory 2,則 select2 應該呈現 Inventory 中的產品2,其他的也一樣。
我的 Ajax 請求(還沒有完成,因為我卡住了):
$('#from-location').on('change', function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "/inventory_products",
dataType: "html", //expect html to be returned
success: function(response){
}
});
});
路線:
Route::get('/inventory-products', array('uses' => 'App\Http\Controllers\LogicForms@inventory_products'));
Controller:
class LogicForms extends Controller
{
public function inventory_products()
{
}
}
表結構:
庫存:ID,名稱
產品:ID,名稱
發票:編號、日期、編號
invoice_products:id,invoice_id,product_id,數量,代碼
product_stocks: id, product_id, inventory_id, invoice_product_id
我認為您的 AJAX 需要將庫存 ID 傳遞給 controller function 並將您收到的產品填充到產品選擇 2 中。
$('#from-location').on('change', function() {
let inventoryId = $(this).val();
$.ajax({
type: "GET",
data: {
inventory: inventoryId
},
url: "/inventory_products",
success: function(response) {
$("#products").select2({
data: response
});
}
});
});
獲取您 controller 中的庫存並返回相關產品,前提是您在庫存和產品之間建立了關系。
應用\模型\庫存.php:
<?php
namespace App\Models;
use App\Models\Product;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
public function products()
{
return $this->belongsToMany(Product::class, 'product_stocks');
}
}
應用\模型\產品.php:
<?php
namespace App\Models;
use App\Models\Inventory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function inventories()
{
return $this->belongsToMany(Inventory::class, 'product_stocks');
}
}
Controller:
class LogicForms extends Controller
{
public function inventory_products(Request $request)
{
$inventory = Inventory::find($request->inventory);
$products = $inventory->products;
$response = collect([]);
foreach ($products as $product) {
$response->push([
'id' => $product->id,
'text' => $product->name,
]);
}
return response()->json($response);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.