简体   繁体   中英

how to bind jquery change event to dynamic tables/rows?

In PHP, I have a dynamic number of tables, and each table has a dynamic number of rows. The last column in the table ($reasonstr) is a drop down list. I want to capture the change in that drop down. If I do this:

                    $('#reason2td3').change(
                     function(){
                        }

I'm able to capture what I need. However, I want this to be dynamic, based on the number of tables and rows on the page.

I have identified the tables & rows as follows:

table, where $id increases with each table on the page:

echo sprintf('<table cellspacing="0" class="myTable" id="myTable%s">',$id);

so, if there are two tables on the page, they are #myTable1 and #myTable2.

rows, where $tdid increases with each row in the table:

                     echo '<tbody>';
                   foreach ($record as $r) {
                        echo sprintf('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>$ %s</td><td>%s</td><td id="reason%std%s">%s</td></tr>',
                             $r['org_number'],
                             $r['dept_descr'],
                             $r['supplier_number'],
                             $r['supplier_name'],
                             $r['invoice_number'],
                             $r['receive_date'],
                             $r['final_qty'],
                             number_format($r['final_cost'],2),
                             $r['inv_status'],
                                $id,
                                $tdid,
                                $reasonstr);
                             $tdid++;
                   }
                  echo '</tbody></table>';
                  $tdid=0;

so, the 3rd row in table 2 is #reason2td3.

How do I capture the $id and $tdid from PHP and use it in JQuery?

Use the attribute starts with selector :

$('[id^="myTable"]').on('change', function(){
   var $id   = this.id;
   // do stuff
});

That will target all elements with an ID starting with myTable, for instance myTable1 , myTable2 , myTableStackOverflowChineseOldMan etc.

Inserting the elements with PHP doesn't really make them dynamic, so delegated event handlers shouldn't be needed for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM