Search code examples
javascriptphpjquerylaraveljquery-selectbox

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


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

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>

Solution

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

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