user3617088
user3617088

Reputation:

Laravel, jquery - Fill input box as per select box

I'm building a Laravel app with jQuery. I've a form with a select box(list of products) and text input fields.

My requirement is when I choose a product from the Select box at the top, the value of all other fields should update according to the products value that is fetched from database for the selected product.

This is my js script:

$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});

My laravel function to return gigs list:

public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;

Can somebody help how to achieve this?

Upvotes: 1

Views: 1541

Answers (2)

Türkalp
Türkalp

Reputation: 188

you can disable unchanged items like following,

$( "#proposed_product" ).change(function() {

    var selectedItem = $(this)

    $.each( $( "#proposed_product" ).children('option'), function (index, item) { 
        if(selectedItem.val() != $(item).val()) {
            $(this).prop('disabled', true)
        }
    })
});

Also, you can change option items by data which result of request you send.

$( "#proposed_product" ).change(function() {

    var selectedItem = $(this)

    // Example Request
    $.get('https://httpbin.org/get', function(data) {
        $.each( $( "#proposed_product" ).children('option'), function (index, item) { 
            if(selectedItem.val() != $(item).val()) {
                $(this).text(data.origin)
            }
        })
    })
});

Also, your response must be json format,

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json($gig, 200);
}

Upvotes: 1

devsourav
devsourav

Reputation: 2531

Make an ajax call to get the data

$( "#proposed_product" ).change(function() {
    $.ajaxSetup({
       headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
       url: "{{ route('your-route') }}",
       type: "POST",
       data: {id: $( "#proposed_product :selected" ).val()}, //send data to controller
       success: function(result){
           console.log(result);
           //check the console then put the data where you want
       }
    });

    $.ajax();
});

In your controller return json response

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json(['data' => $gig]);
}

Upvotes: 1

Related Questions