Can't submit the right button for each input field [multiple buttons and input fields in a single form]

Viewed 170

Im kind of new to jquery and ajax and im wondering if someone could help me out?

I have php foreach loop that print out one input type = number and a button. The code below, creates a table with where each row show the item name, a box for the user to enter quantity and a button to sell the item.

<div class=verktyg>
    <form action='sell_items.php' method='POST' id='ajax'>
        <table class="inventory">

<?php
    foreach (array_slice($items, 2) as $key => $value) {

        if($value>0){

            echo "<tr>  
                 <td id='verktyg-first-td'>".$key."</td>
                 <td>".$value."</td>
                 <td><input type='number' name='items[$key]' value='0'></td>
                 <td><button type='submit' name='item' value='$key'>sell</button></td>
                 </tr>";
            }
      }
?>  
        </table>
    </form>
</div>

And this is my jquery/ajax code:

$(document).on('submit','form#ajax', function(){
            var that = $(this); 
                url = that.attr('action');
                type = that.attr('method');
                data = {};

            that.find('[name]').each(function(index, value){
                var that = $(this);
                        name = that.attr('name');
                        value = that.val();
                        data[name] = value;
                });

            $.ajax({
                url: url, 
                type: type, 
                data: data,
                success: function(response) {
                console.log(response);
                }
            });

            return false;
        });

Now to the problem. When i try to sell 2 units of the first item (in the first row) my form thinks im submitting the last input field (in the last row), when im not..

This is what i get in browser console when i try to sell 2 units of the first item:

Console.log(response): See my ajax response in console when i click sell item in the first row

Console.log(data): See my ajax data in console when i click sell item in the first row

I tried to start my js script with:

$('form#ajax').on('submit', function(){

instead of

$(document).on('submit','form#ajax', function(){

But it did not work.. Any ideas?

EDIT: I might be approaching this problem the wrong way.. Now im thinking maybe i should find the button that was clicked and then get the previous element's value by writing something like this:

var btn= $(this).find("button[type=submit]:focus").val();
        var quantity = $(btn).prev("input[type=number]").val();
        console.log(btn);
        console.log(quantity);

But still, my quantity is undefined. Need to figure a way to obtain that value...

Thanks in advance

1 Answers
Related