Show value from selected dropdown in laravel

Viewed 853

I want to show the detailed address of a selected recipient name from a dropdown menu. So, if I choose address A, it will display the details of address A. I'm already working on the code but the issue is it doesn't show the correct value, instead it shows the last record in the database. Here's the code:

Blade

<select class="address-detail form-control" id="address" name="address_detail" data-target=".detail-info-address">
    <option value="option_select">Select Address</option>
        @foreach($addresses as $address)
            <option value="{{$address->id}}"  data-show=".info-address">{{$address->recipient_name}}
            </option>
        @endforeach
</select>

<div class="detail-info-address">
    <div class="info-address hide text-left">
        <p>Recipient Name: {{$address->recipient_name}}</p>
        <p>Contact Number: {{$address->contact_number}}</p>
        <p>Address: {{$address->address}}</p>
        <p>Address Note (optional): {{$address->address_note}}</p>
        <p>Post Code: {{$address->post_code}}</p>
        <p>Province: {{$address->province}}</p>
        <p>City: {{$address->city}}</p>
        <p>District: {{$address->district}}</p>
        <br>
    </div>
</div>

Controller

public function buynow($id) {
    $addresses = Address_Delivery_Users::where('user_id', '=', Auth::user()->id)->get();

    return view('/transactions/delivery', compact('addresses'));
}

Javascript

<script>
    $(document).on('change', '.address-detail', function() {
        var target = $(this).data('target');
        var show = $("option:selected", this).data('show');
        $(target).children().addClass('hide');
        $(show).removeClass('hide');
    });

    $(document).ready(function(){
        $('.address-detail').trigger('change');
    });
</script>
1 Answers

Your problem is that the variable $address is defined in the foreach loop, therefore the last element of the loop will be set to $address.

Hence, your address block will always contain the attributes of the last address element. After initial rendering of the page, you are not able to display another address in the PHP variable $address.

It is important that you differnetiate between PHP which is server-side and JS which is client-side.

You will have to listen to the change event of the select and get the new data. There are two options for that.

  1. You make an ajax request to your server and return the address-object and set all fields correspondingly.

  2. In your foreach loop you add for every attribute of your address a data-<varaible_name> html attribute and onchange get all data- attributes and insert them in the correct fields of your address block.

I would recommend using Vue.js for this task. However if you are new and don’t have much experience at all you might try plain JS/Jquery at the moment.

Related