当我从选择框中选择产品时,如何获取相关产品的价格?
我正在从数据库(Laravel Mysql 项目)获取产品名称和价格。 我想在价格文本框中显示价格。 以下是我的看法`
<form role="form">
<div class="form-group">
<label for="Vehicle"> Vehicle Name:</label>
<select class="form-control">
@foreach($servicevehicles as $servicevehicle )
<option>{{$servicevehicle->vehiclename}}</option>
<!--here dispaly vehicle name-->
@endforeach
</select>
</div>
<div class="form-group">
<label for="price"> Price</label>
<!--i want to display related product when i select related vehicle from above selectbox-->
<input type="text" class="form-control" >
</div>
</form>
最佳答案
我建议您在选项标签中将价格打印为数据属性,如下所示:
$('.vehicle-type').on('change', function() {
$('.price-input')
.val(
$(this).find(':selected').data('price')
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form">
<div class="form-group vehicle-type">
<label for="Vehicle"> Vehicle Name:</label>
<select class="form-control">
<option data-price="345">Title 1</option>
<option data-price="122">Title 2</option>
</select>
</div>
<div class="form-group">
<label for="price"> Price</label>
<input type="text" class="form-control price-input" readonly>
</div>
</form>
然后使用 JS (jQuery) 监听 Change 事件以从所选选项中提取新值。 这应该可行。
关于javascript - 当我从选择框中选择产品时,如何获取相关产品的价格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48437891/