0

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>

an Image of my table

2 Answers 2

1
  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);
    
Sign up to request clarification or add additional context in comments.

2 Comments

I like your first method , but my table is quiet complicated , i have more than 10 tds and in each td a big load of information , so I'm afraid this won't be possible or my code will be really messy.
use loop to generate td
1

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>

10 Comments

Yes , but how I can implement it in my case ? using my loop
@NoureddineBrahmi there is a different event in jquery you can add dynamically in any row or column.
@NoureddineBrahmi if you still have a doubt please add your code in jsfiddle I will help you out from this.
This is my jsfiddle link and thanks a lot for your help !
@NoureddineBrahmi check my answer I updated it also you can check js fiddle link
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.