Jump to content

Targeting an element inside a PHP loop using jQuery


Go to solution Solved by WinstonLA,

Recommended Posts

I want to fetch items from a database and be able to update their quantity by selecting a number from a drop down selection and press the button "Update quantity" to perform the action.

I have the following php code:

echo    '<table border="4">
            <tr>
                <th>ID</th>
                <th>Item Name</th>
                <th>Current Quantity</th>
                <th>New Quantity</th>
                <th>Update</th>
            </tr>';

for($i=0 ;$i<$k; $i++)

$z = $i+1;

//fetch data from database
$id = the id of the row that the entry/item is at
$item_name = the name of the item
$current_quantity = the current quantity of the item

//create a table of entries


         echo   '<tr'>
                    <td>'.$z.'</td>
                    <td>'.$item_name.'</td>
                    <td>'.$current_quantity.'</td>
                    <td>

                        <select id="quantity" name="quantity">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                               .
                                               .
                                               .
                        </select>

                    </td>';

            echo    '<td>

                          <button type="button" value="'.$id.'" name="updatebtn" id="updatebtn">Update Quantity</button>

                    </td>';

      echo    '</tr>';

Where k = number or matches in database

The result is something like this:

////////////////////////////////////////////////////////////////////////////
///ID // Item Name // Current Quantity // New Quantity //    Update      ///
////////////////////////////////////////////////////////////////////////////
// 1 //   Shoes   //       10          //      12      // Update Quantity //
////////////////////////////////////////////////////////////////////////////
// 2 //  T-shirts //        5          //       8      // Update Quantity //
////////////////////////////////////////////////////////////////////////////
// 3 //  Watches //         4          //       2      // Update Quantity //
////////////////////////////////////////////////////////////////////////////

The first 3 columns are populated by the database and New Quantity by the user. As soon as the user is done with the new quantity he/she presses "Update Quantity" to update the database.

Below is the jQuery code i use:

$(document).ready(function(){

 $('#updatebtn').click(function(){

    //i use this value to find the exact entry in the database
    var id = $('#updatebtn').attr('value');

    var quantity_selected = $('select#quantity option:selected').attr('value');

    $.ajax({

                type: "POST",
                url: "js/ajax/updatequantity.php",
                data: {id: id, new_quantity: quantity_selected}

            });


   //this is for testing        
   alert('ok');

 });
});

The updatequantity.php script just takes the new quantity and the row of the entry and updates the value.

My problem is:

If i press the "Update Quantity" of the item "Shoes", i see the pop-up "ok" and the quantity is updated. But when i try to do the same for the 2 other items (T-shirts and watches), i get nothing.

Does my js script has trouble to differentiate between the "Update Quantity" buttons? Is there another approach?

ps: i am doing this using wamp on my localhost

Thanks in advance.

  • Solution

Try like this

for ($i = 0; $i < $k; $i++) {
    $z = $i + 1;
    
    //fetch data from database
    $id               = 'the id of the row that the entry/item is at';
    $item_name        = 'the name of the item';
    $current_quantity = 'the current quantity of the item';
    //create a table of entries
    echo '<tr>
<td>' . $z . '</td>
<td>' . $item_name . '</td>
<td>' . $current_quantity . '</td>
<td>


<select id="quantity' . $i . '" name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>


</td>';
    echo '<td>
 <button type="button" value="' . $id . '" name="updatebtn" class="quantity_updatebtn">Update Quantity</button>
</td>';
    echo '</tr>';
}
$(document).ready(function(){
 $('body').on('click', '.quantity_updatebtn', (function(){


    //i use this value to find the exact entry in the database
    var id = $(this).attr('value');


    var quantity_selected = $(this).closest('tr').find('select[id^="quantity"] option:selected').val();


    $.ajax({
type: "POST",
url: "js/ajax/updatequantity.php",
data: {id: id, new_quantity: quantity_selected}


});




   //this is for testing        
   alert('ok');


 });
});

 

You can not use an id for the update button as ids can only be used once. As you have multiple update buttons you should use a class  class="updatebtn"   and use   .updatebtn  as the selector

 

Now to get the id value from the update button that was clicked you need to pass   this   to the selector to get the attribute value for the button that was clicked.

var id = $(this).attr('value');

As you are using the product id for associating the update button with the item. You can do the same with the dropdown menu by naming it using this   <select name="quantity['.$id.']">

 

Now in your Jquery code you can use the following to get the quantity for the item

var quantity_selected = $('select[name="quantity['+id+']"] option:selected').attr('value');

// for debug purposes show quantity for product id being updated
alert('The quantity for item id '+id+' is being updated to '+quantity_selected);

You can see Live demo here  for the JQuery code.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.