regit
regit

Reputation: 17

Laravel: Generated buttons with loop (How to tell which one is click)

Hello Again Stockoverflow, Hope all is well with you,

Can you help me again with Laravel/Ajax?

From the given code below I generated the table shown on the picture, what I want to accomplish is to save each row when a button is click, I know enough ajax to do the saving, the problem is how can I tell ajax and jquery which row button is click and which text input has the value since, the text inputs and buttons are generated with loop/array?

Thanks.

            if($list_factors)
        {
            foreach ($list_factors as $key => $list_factor) {
               // dd($list_factors);
                $output.='<tr>'.
                '<td>'.$list_factor->id.'</td>'.
                '<td>'.$list_factor->factor_description.'</td>'.
                '<td><input type="text" id="score" /></td>'.
                '<td><button class="btn btn-info" id="submitScore">OK</button></td>'.
                '</tr>';

            }
            return Response($output);
        }

Table pic.[1]

Upvotes: 0

Views: 170

Answers (1)

The Alpha
The Alpha

Reputation: 146191

First of all, you can't use id="submitScore" attribute in the button generated within the loop because id must be unique. Instead you can use class="submitScore". Also, you can't use id="score" in the input, use class="score" Since you are going to use jQuery then you may try something like this:

// Register the event handler on 'submitScore' class of button
$('button.submitScore').on("click", function(e) {
    var row = $(this).closest('tr');
    var inputValue = row.find('.score').val();
    console.log(inputValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
    <tr>
        <td><input class='score' /></td>
        <td><button class='submitScore'>OK</button></td>
    </tr>
    <tr>
        <td><input class='score' /></td>
        <td><button class='submitScore'>OK</button></td>
    </tr>
 </table>

Upvotes: 1

Related Questions