How to add row to GridView widget with JavaScript

Is there a way to add a row to a GridView-generated table with JavaScript without reloading the page? I don’t want to save the data to the database. I just want to add a row to a table.

Yes you can do it:




<a href="#" class="add-row">Add Row</a>


<script>

    $(document).ready(function(e) {

       var $table = $('#milestone-grid table tbody');

       $('.add-row').click(function(e) {

         //If it is odd then the next one should be even.. 

         var number = (($table.find('tr').size())%2 === 0)?'odd':'even';

         var html = '<tr class="'+number+'"> <td>Added</td> </tr>';

         $table.append(html);

         return false;

       });

    });

    

</script>

where #milestone-grid is the table ID you need to replace.

That will do. Thanks!

That worked great! Thank you!

What if I want to save the data? I’ve been reading all the editable documentation, but it seems to use detailview and not gridview and I can’t seem to bridge this in my mind.

I have an editable gridview and that is working great for updates. I would like to have a button below the editable rows that says “Add new” and then pop in a new row of input fields (that worked great with the code above) with a Create/Add button that would allow the user to save the new record. I can’t seem to get this working.

As a workaround, I will pop up a detailview for a new record and refresh the gridview, but would like to make it more streamlined by keeping the "add" inline.

Any help would be appreciated.

Hello,

in my experience i have obteined the same result as:




var $table = $("#id-table").children('table');

var $tbody = $table.children('tbody');

$tbody.append('<tr> <td>Some Text</td> <td>Some Text</td>  </tr>');



Best regards!!!