Latest

Thursday, July 13, 2017

Each row in a table has a drop-down. How do I retrieve both the select value, and an id of each row and save it to database?

Asked by: derrickrozay


I have a table with an "Approve" and "Reject" dropdown select for each row (can be as many as 10 rows). When the user clicks submit I want get the value of what they selected for each row and do a bulk update.

How can I retrieve these values in the controller when posting via ajax?

<table class="col-md-12 table-bordered">
    <thead>
    <tr>
        <th>ItemCode</th>
        <th>Description</th>
        <th>Quantity</th>
        <th>Approve/Reject</th>
    </tr>
    </thead>
    <tbody>
        @foreach ($order as $product)
            <tr>
                <td>{{$product->itemcode}}</td>
                <td>{{$product->description}}</td>
                <td>{{$product->quantity}} {{$product->uom}}</td>
                <td data-title="Approve/Reject">
                    <select name="statusSelect[]" id="statusSelect" class="form-control">
                        <option id="{{$product->id}}" value="Approved">Approve</option>
                        <option id="{{$product->id}}" value="Rejected">Reject</option>
                    </select>
                </td>
            </tr>
        @endforeach
    </tbody>
</table>
    <div class="btn btn-primary" onclick="save()"></div>

save.js

function save() {

    let order = [];

    $('select[name="statusSelect[]"]').each(function(){
        let id = this[this.selectedIndex].id;
        let value = this.value;
        order.push({id: id, status: value});
    });

    console.log(order);
    let data = JSON.stringify(order);
    console.log(data);

    $.ajax({
        method: 'put',
        url: '/api/order/'
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(response){
            //console.log(response);
        },
        error: function(data){
            console.log(data);
        }
    });
}


Source

No comments:

Post a Comment

Adbox