我想显示所选下拉列表中的详细信息。所有详细信息都来自数据库。问题是,当用户选择1个下拉值时,价格没有显示。我错过了哪一部分?这是我的代码:
路线:
Route::get('/prodview', [OrderController::class, 'prodfunct']);
Route::get('/findPrice', [OrderController::class, 'findPrice']);
控制器:
public function prodfunct()
{
$prod=DB::all();//get data from table
return view('orders.order',compact('prod'));//sent data to view
}
public function findPrice(Request $request){
//it will get price if its id match with product id
$p=DB::select('select price from pastas')->where('id',$request->id)->first();
return response()->json($p);
}
视图:
<span>
<x-label for="pastaingredient" :value="__('Pasta Ingredient: ')" />
<x-input id="pastaingredient" style="font-size:14px;" class="pasta_ingredient" type="text" name="pastaingredient" value="{{ old('pasta_ingredient') }}" disabled />
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change', '.pastas', function()
{
var ingredient = $(this).find("option:selected").data("ingredient");
$('.pasta_ingredient').val(ingredient);
});
});
</script>
实现这一点的其他方法是将价格值存储为data-attribute
,然后每当用户从选择框中选择任何值时,您可以简单地使用$(this).find("option:selected").data("price")
从选项中获取值。
因此,您只需要将data-price="{{ $pizzaitem->price }}"
添加到您的选项中,即:
<option @if(old('pastas') == $pizzaitem->name) selected @endif value="{{ $pizzaitem->name }}" data-price="{{ $pizzaitem->price }}">{{ $pizzaitem->name }}</option>
然后,您的jquery代码将如下所示:
$(document).on('change', '.pastas', function() {
var price = $(this).find("option:selected").data("price");
$('.prod_price').val(price);
});
var a=$(this).parent();
返回this
的直接父级。在这种情况下,a
是这样的div:
<div>
<x-label for="pastas" :value="__('Choose pastas:')" />
<select name="pastas" id="pastas" class="pastas">
<option @if(!old('pastas')) selected @endif disabled>Please choose</option>
@foreach ($pastainfo as $pizzaitem)
<option @if(old('pastas') == $pizzaitem->name) selected @endif value="{{ $pizzaitem->name }}">{{ $pizzaitem->name }}</option>
@endforeach
</select>
</div>
因此在这一行a.find('.prod_price').val(data.price);
JQuery只在a
div中找到prod_price
,而在那里看不到它,导致了这个错误。