当我从选择框中选择产品时如何获得相关产品的价格?

问题描述:

当我从选择框中选择产品时,如何获得相关产品的价格?

How to get the price of the related product, when I select the product from selectbox?

我正在从数据库中获取产品名称和价格(Laravel Mysql项目). 我想在价格文本框中显示价格. 以下是我的观点`

I am fetching product names and prices from database (Laravel Mysql project). I want to display price on price text box. Following is my view`

<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>

我建议您将价格作为数据属性打印在选项标签中,如下所示:

I would recommend you to print the price as data-attribute in the option tag like this:

$('.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事件,以从所选选项中提取新值. 这应该起作用.

Then with JS (jQuery) listen to the Change event to extract new value from the selected option. This should work.