简体   繁体   中英

Adding a row to a table dynamically using jQuery

I have this table and I want to be able to add rows to it dynamically using Jquery but I'm falling so far, I already have a loop in place for the added rows, I just need the script that goes with it. (I'm using a MVC pattern design)

My code for the loop :

<?php
     $viewTableRows = array_merge($device->tableRows, array(new tableRow()));
     foreach ($viewTableRows as $i => $row) { 
  ?>

an example of a td:

<td>
       <?php echo $htmlRenderer->getProperHtmlForInputText(
           SheetTableOperator::SHEET_POSITION .  "[$i]",
           $row->position);
       ?>
</td>

我桌子的图像

Use this code to add data dynamically.

        <button id='mybtn'>Add row</button>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous"></script>

<script  type="text/javascript">
           $(document).on("click",'#mybtn',function(){  

                 var $mytable = $('#table').find("tbody");

                  $last_row = $mytable.find("tr:last");

                  $new_row = $last_row.clone();

                  $last_row.after($new_row);

           });    


</script>
  1. Method 1

     var currentEletd; $('table').append("<tr class='tr'></tr>").after( function() { var ele = $('.tr', this); currentEletd = (ele[ele.length - 1]); }); $(currentEleth).append(("<td>" + [your value] + "</td>")); 
  2. Method 2

     mytbody=$("<tbody></tbody>"); mytr = $("<tr></tr>"); mytr.append("<td></td>"); $('table').append(mytbody); 

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