add a row to a jquery datatable. for editing

I have a datatable that is loaded on my page....and I just need to insert a row so my user can input data and save. I cannot  seem to make this happen....

Here is the jquery table referenced in the view:  I would think I could reference that table since its already loaded on page but having no luck.  Please help.

The columns that are rendered with existing data are Entity, Role, Designate, Allocation

within the jquery grid I am dynamically pulling the data ...Entity would be autopopulated, Role would load a dropdown, designate would load a drop down, and allocation would be a input for decimal values.  Then there would be an save and cancel button


<div class="col-xs-12">
        <div class="row" style="margin-bottom:4px;">

            @BootstrapHelper.Panel("GenericGrid-panel", BootstrapPanelCssClass.Primary, @Model.HeaderTextLeft, "",
                        false, @Model.Icon, "GenericGrid-panel-body", "",
                        @<text>

                            <div id="contactEntity-crud-div" class="col-xs-12" style="float:left;display:block">
                                test
                                <div id="main-container-contactEntity" class="container-fluid">

                                    <table id='contactEntity-crud' class="display" style="width:100%;"><tbody></tbody></table>
                                </div>
                            </div>
                        </text>, "", "",@<text>  </text>)




        </div>
    </div>

Open in new window

LVL 11
Robb HillSenior .Net DeveloperAsked:
Who is Participating?
 
Leonidas DosasCommented:
In general, what you can do is create a row object and then within that row object whenever you run a loop to place the prices on the corresponding children of the item .
0
 
Leonidas DosasCommented:
Do you use  the jquery datatables plugin?
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
im using the jquery library for datatables.

This table is loaded on the page by an external js file.....it handles way more than this table....

My table loads on page fine.....its just I cannot add a row.

Do I need to recall the data just to let user add a row at the top or bottom of the table..preferablly the top
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Robb HillSenior .Net DeveloperAuthor Commented:
this is alot of overkill..but maybe it can help you understand how this is working......im guessing I need to build an insertrow method in this js file.

var Page = {};
function loadGridAsync(grids, siteCode, dataWhereClause, searchFor, sortBy, childRowUrl) {
    

    setTimeout(function () {
        loadGrid(grids, siteCode, dataWhereClause, searchFor, sortBy, childRowUrl);
    }, 0);

}

function loadGrid(grids, siteCode, dataWhereClause, searchFor, sortBy, childRowUrl) {

    var schemaResults;
    var columns;
    var columnDefs;
    var errorMessage;

    
    if (siteCode == null ||  siteCode == "") {
        siteCode = "";
    }
    else {
        siteCode = "," + siteCode + ","; // to provide delimiters on both sides;
    }

    var gridNameArr = grids.replace(' ','').split(',');

    for (var g in gridNameArr) {

        var gArr = gridNameArr[g].split('^');
        var gridName = gArr[0];
        var afterRenderCallBack = gArr[1];
        var $this = UI.Html;
        var $cUtil = Utilities;
        var $cMesg = UI.Messenging;
        var schemaApi = "/GenericGrid.mvc/GenericGridDataTable?gridName=" + gridName + "&sitecode=" + siteCode + "&searchFor=" + searchFor + "&mode=schema&SessionID=" + Conarc.Utilities.Http.getSessionId();
        var dataApi = "/GenericGrid.mvc/GenericGridDataTable?gridName=" + gridName + "&sitecode=" + siteCode + "&searchFor=" + searchFor + "&mode=data&SessionID=" + Conarc.Utilities.Http.getSessionId() + "&whereClause=" + encodeURIComponent(dataWhereClause);
        var propertiesApi = "/GenericGrid.mvc/GenericGridDataTable?gridName=" + gridName + "&sitecode=" + siteCode + "&searchFor=" + searchFor + "&mode=props&SessionID=" + Utilities.Http.getSessionId();

        $.ajaxSetup({
            async: false
        });

        var schemaPromise = [$.getJSON(schemaApi)];
        $.when.apply($, schemaPromise).done(function (schemaData) {

            //check if data came from WebAPI or MVC controller (string vs object)

            if (!$cUtil.String.isNullOrEmpty(schemaData)) {
                schemaResults = JSON.parse(schemaData);
            } else {
                schemaResults = schemaData;
            }
            if (!$cUtil.Object.isNullOrNotObject(schemaResults)) {

                var tableElementId = gridName;
                var tableHtml = $this.getHtmlTableByColumns(schemaResults, tableElementId, '');
                var containerIdSelector = "#" + tableElementId;

                if ($(containerIdSelector).length > 0) { 
                    $(containerIdSelector + "-div").empty().append(tableHtml);
                }


                $(containerIdSelector + "-div").show();

                //get column arrays
                columns = $this.getDataTableColumns(schemaResults);
                columnDefs = $this.getDataTableColumnDefs(schemaResults);

                var sortIndex = 0;
                var sortDirection = "asc";
                var sColumns = "";

                $.ajaxSetup({
                    async: false
                });

                //get datatable properties
                $.ajax({
                    type: "GET",
                    url: propertiesApi,
                    cache: false,
                    dataType: "html",
                    success: function (data) {

                        var a = jQuery.parseJSON(data)[0];
                        if (a === undefined) {
                            return;
                        }

                        $("#hSortBy").val(a.defaultSortColumn);

                        // find a[0].defaultSortColumn in sColumns to set order #
                        var c = 0;
                        columns.forEach(function (e) {
                            sColumns += e.data + ",";
                            if (e.data.toLowerCase() == a.defaultSortColumn.toLowerCase()) {
                                sortIndex = c;
                            }
                            c++;
                        });

                        if (a.sortDescending) {
                            sortDirection = "desc";
                        }

                        $.fn.dataTable.ext.errMode = function (settings, helpPage, message) {
                            console.log(message);
                        };


                        $.ajaxSetup({
                            async: false
                        })

                      
                        $.ajax($(containerIdSelector).DataTable({
                            dom: '<"top"f>rtip',
                            ajax: dataApi + "&sSortColumn=" + a.defaultSortColumn + "&sSortDir=" + sortDirection,
                            deferRender: true,
                            scrollY: a.height,
                            scrollCollapse: a.collapse,
                            scrollX: true,
                            responsive: false,
                            scrollcollapse: true,
                            scroller: true,
                            columns: columns,
                            columnDefs: columnDefs,
                            autoWidth: true,
                            fixedColumns: {
                                heightMatch: 'auto'
                            },
                            destroy: true,
                            bFilter: a.showSearchBox,
                            sColumns: sColumns,
                            order: [[sortIndex, sortDirection]],
                            info: a.collapse,  // hide "Showing x of y" RSS TODO NEED Separate option for grids

                            "createdRow": function (row, data, index) {
                                if (data.dueDateLate) {
                                    $('td', row).eq(4).addClass('dueDateLate')
                                };
                            },



                        })).success(function (data) {

                            var table = $(containerIdSelector).DataTable();
                            table.columns.adjust().draw();

                            window.onresize();

                            var fn = window[afterRenderCallBack];
                            if (typeof fn === "function") {
                                fn();
                            }

                            $(containerIdSelector).addClass('cell-border');

                            // set up event to display child rows
                            if (childRowUrl != '') {

                                $('#' + gridName + ' tbody').on('click', 'td.expand', function (e) {
                                    getChildRows(e, gridName, childRowUrl);
                                });
                            }
                            
                        }).fail(function (error) {

                            alert(error.responseText);
                        });

                        $(containerIdSelector + "-div").show();
                       
                    },
                    error: function (data) {
                        alert(data.responseText);
                    }
                });


            } //end of if schemaResults object check
            else {
                errorMessage = "Error: couldn't convert schema information from API to object.  Please contact support.";
                $cMesg.getErrorPopup(errorMessage, "Error: Schema Loading", 9000);

            } //end of else schemaResults not object

            var table = $(containerIdSelector).DataTable();
            $("#contentArea").show();
            table.columns.adjust().draw();
 
        });

    }
}


function StreamFile(title, documentCode) {
    UI.Messenging.getInfoPopup(title, "Getting ...");
    window.open("/wc.dll?CADOC~CADOCMANAGE~DMDOCUMENTS~FILESNAP~" + documentCode);
}

//function PrintFile(title, documentCode) {
//    UI.Messenging.getInfoPopup(title, "Getting ...");
//   // window.print("/wc.dll?CADOC~CADOCMANAGE~DMDOCUMENTS~FILESNAP~" + documentCode);
//}

function CollapseGrid(gridBodyId, gridId) {
    $('#' + gridBodyId).hide();
    $('#collapseGridIcon-' + gridId).hide();
    $('#expandGridIcon-' + gridId).show();
}

function ExpandGrid(gridBodyId, gridId) {
    $('#' + gridBodyId).show();
    $('#collapseGridIcon-' + gridId).show();
    $('#expandGridIcon-' + gridId).hide();
}

function getQueryVariable(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function AdjustColumns(gridName) {
    
    if (gridName == '') {
        gridName = $("#hGridName").val();
    }
    
    var table = $("#" + gridName).DataTable();
    table.columns.adjust().draw();
 
}
function ReDrawTable() {

    // where we are is saved here... retrieve it
    var gridName = $("#hGridName").val()

    var siteCode = $("#hSiteCode").val();
    var dataWhereClause = $("#hWhereClause").val();
    var searchFor = $("#searchBox").val();
    var sortBy = $("#hSortBy").val();
    var childUrl = $("#hGetChildUrl").val();
    loadGridAsync(gridName, siteCode, dataWhereClause, searchFor, sortBy, childUrl);
}

function expandRow(e, table, row, tr, data) {
   
    if (row.child.isShown()) {
        $(tr).removeClass('shown');
        row.child.hide();
    }

    else {
   
        var tmpRow = table.row.add(data).draw().node();

        row.child($(data)).show();
        $(tr).addClass('shown');

        table.row(tmpRow).remove().draw();
       
    }

};

Open in new window

0
 
Robb HillSenior .Net DeveloperAuthor Commented:
I dont follow....

So for me to execute the following javascript above I call this.:  Now this is hardcoding some values..but basically it goes to my database.....to get the structure of the table....then calls the javascript above...where the loadgrid is the big call.  After this is called...my page loads up with a grid of column headers, and data from my sql database...and some dynamic buttons.    I just want to be able to add a row now..so a user can insert new data into this table.

    $(document).ready(function () {

     var grids = "contactEntity-crud";
     $("#GenericGrid-panel").show();
     var sortBy = $("#hSortBy").val();
     loadGridAsync(grids, "", "contactId=69789", "", sortBy,"");
    });

Open in new window

0
 
Robb HillSenior .Net DeveloperAuthor Commented:
i added this...and it appears that it adds the row...but you cannot actually see anything.....but the row count increments.....not sure what this means at this point..  I just put fake info in...as I would really be adding controls.not data.


    function addNewRow(){
        var table = $('#contactEntity-crud').DataTable();
 table.row.add( [
            'New row',
            'Test 2',
            '123',
            '2014-05-09',
            'button1',
            'button2'
        ] ).draw();
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.