Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 988
David Mozart Andraws Avatar asked Oct 29 '22 07:10

David Mozart Andraws


1 Answers

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

Yes you're correct on this one. You should take this approach.

I've made a sample code for you to use:

HTML:

<div class=verktyg>
  <form action='sell_items.php' method='POST' id='ajax'>
    <table class="inventory">
      <tr>
        <td class='verktyg-first-td'>Item 1</td>
        <td>10</td>
        <td>
          <input type='number' name='item_1' value='10'>
        </td>
        <td>
          <button type='submit' class='submit_button'>sell</button>
        </td>
      </tr>
      <tr>
        <td class='verktyg-first-td'>Item 2</td>
        <td>20</td>
        <td>
          <input type='number' name='item_2' value='20'>
        </td>
        <td>
          <button type='submit' class='submit_button'>sell</button>
        </td>
      </tr>
    </table>
  </form>
</div>

Jquery:

 // prevent for submission
 $("form").submit(function(e) {
   e.preventDefault();
 });

 // when submit button is clicked
 $(".submit_button").on("click", function() {
   self = $(this);
   form = self.closest("form");
   url = form.attr('action');
   type = form.attr('method');
   parentTr = self.parent("td").closest("tr"); // get the parent <tr>
   data = {};

   inputElm = parentTr.find("input[type=number]"); // find input element closest to the clicked button
   name = inputElm.attr('name'); // get input name
   value = inputElm.val(); // get input val
   data[name] = value;

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

So first, I fixed some issues on your code. Like having multiple the same ID when you did a loop id='verktyg-first-td'. So I changed that to class instead.

And I changed how you triggered your function. Instead of triggering when the form is submitted, trigger it when the button is clicked.

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

var quantity = $(btn).prev("input[type=number]").val();

Yes, that would work if your structure is:

    <td>
      <input type='number' name='item_1' value='10'>
      <button type='submit' class='submit_button'>sell</button>
    </td>

But the input element you were looking for is inside another <td>.

So you have to find first the closest <tr>

parentTr = self.parent("td").closest("tr");

then look for that input[type=number].

inputElm = parentTr.find("input[type=number]");

Update:

if(isset($_POST['item'])) dosent detect the button click and says "Undefined index: item"

First to fix this, re add the attributes back to the button element.

e.g.

<button type='submit' class='submit_button' name="item" value='button_value'>sell</button>

then add this code below after data[name] = value;

// get button val
value = self.val();
name = self.attr('name');
data[name] = value;
like image 87
Robin Carlo Catacutan Avatar answered Nov 13 '22 02:11

Robin Carlo Catacutan