Jquery DataTable not working after appending the html code to DataTable using jQuery

Ashok Kumar 201 Reputation points
2024-05-06T13:26:54.2166667+00:00

I have created a datatable and appending the data to that datatable body , data appending successfully but the datatable not working properly

ex:- If I click on the datatable header columns the entire table data is erasing.

Here is my full logic

Asp.net code:-


<asp:Button ID="sb_add" runat="server" OnClientClick="return SB_Add_Legs(event);" Text="+ ADD" CssClass="btn btn-primary w-100 w-md-auto text-center px-4" />

       <table class="table table-borderless rowSpace table-round-row dtr-inline  SB_table dataTable nowrap "

                            id="strastrategy_builder_datatable" style="width: 100%;">

                            <thead>

                                <tr>

                                    <th>Action</th>

                                    <th>Instrument</th>

                                    <th>Expiry</th>

                                    <th>Strike</th>

                                    <th>Qty</th>

                                    <th>Future Price</th>

                                    <th>Price</th>

                                    <th>Delta</th>

                                    <th>Gamma</th>

                                    <th>Theta</th>

                                    <th>Vega</th>

                                    <th>IV</th>

                                    <th data-dt-order="disable"></th>

                                </tr>

                            </thead>

                            <tbody>

			</tbody>

                        </table>

                        <div class="sbnolegs">NO LEGS ADDED</div>

Datatable logic :-


$("#strastrategy_builder_datatable").find("th").off("click.DT");

    $('#strastrategy_builder_datatable').DataTable({

        ordering: false,

        info: false,

        paging: false,

        searching: false,

        responsive: true,

        language: {

            emptyTable: ' ',

        },

        columnDefs: [

            {

                width: '100px',

                responsivePriority: 1,

                targets: 0

            },

            {

                className: 'dt-center',

                width: '50px',

                responsivePriority: 2,

                targets: -1

            },

            {

                width: '110px',

                // responsivePriority: 3,

                targets: -2

            },

            {

                width: '110px',

                responsivePriority: 4,

                targets: -3

            },

            {

                width: '110px',

                responsivePriority: 5,

                targets: -4

            },

            {

                width: '110px',

                responsivePriority: 6,

                targets: -5

            },

            {

                width: '110px',

                responsivePriority: 7,

                targets: -6

            },

            {

                width: '100px',

                responsivePriority: 8,

                targets: -7

            },

            {

                width: '100px',

                responsivePriority: 9,

                targets: -8

            },

            {

                width: '120px',

                responsivePriority: 10,

                targets: -9

            },

            {

                width: '120px',

                // responsivePriority: 10,

                targets: -10

            },

            {

                width: '160px',

                // responsivePriority: 10,

                targets: -11

            },

            {

                width: '100px',

                // responsivePriority: 10,

                targets: -12

            }

        ]

    });

Add button logic function :-


function SB_Add_Legs(e) {

    e.preventDefault();

    //console.log("data :- " + data);

    var d_stg = '';

    var s_leg_data = "";

    var b_selected = '';

    var s_selected = '';

    var ddl_expdate = "";

    var ddl_strike = "";

    //$("#strastrategy_builder_datatable").removeClass('hidden');

    var lnt = $("#strastrategy_builder_datatable .aliceBlueRow").length;

    //if (lnt === 1)

    if (lnt < 10) {

        var s = $("#sb_smbl_srch").val(); // textbox val

        var s_bs = $("#sb_buysell").val();   // dropdown val

        var s_inst = $("#sb_instrument").val(); // dropdown val

        var s_stk = $("#sb_strikeprice").val(); // dropdown val

        var s_ex = $("#sb_expdate").val(); // dropdown val

        var s_q = $("#sb_qty").val(); // textbox val

        d_stg = LTP_AJAXCall(s, s_ex, s_stk, s_inst, s_bs);

        

         console.log(d_stg);

/*[

    {

        "Price": "137.45",

        "Delta": "0.5085",

        "Gamma": "0.0012",

        "Theta": "-24.5206",

        "Vega": "8.1152",

        "IV": "16.64",

        "OI": "1637425.00",

        "OIChg": "835625.00",

        "FuturePrice": "22559",

        "StrikeType": "ATM",

        "LotSize": "25"

    }

]*/

        

        //SB_Legs_Added_Load("add", d_stg);

        //$("#strastrategy_builder_datatable tbody").empty();

        if (d_stg && d_stg.length > 0) {

            $.each(d_stg, function (index, rowData) {

                ddl_expdate = "";

                ddl_strike = "";

                if (s_bs.toLowerCase() === 'buy') b_selected = 'selected', s_selected = ''; else b_selected = '', s_selected = 'selected';

                var drpInstrumentValue = s_inst.toUpperCase();

                var d_exp = s_ex;

                var d_stk = s_stk;

                var ddl_inst = `

                    <option value="CE" ${drpInstrumentValue === "CE" ? "selected" : ""}>CE</option>

                    <option value="PE" ${drpInstrumentValue === "PE" ? "selected" : ""}>PE</option>

                    <option value="FUT" ${drpInstrumentValue === "FUT" ? "selected" : ""}>FUT</option>

                    <option value="EQ" ${drpInstrumentValue === "EQ" ? "selected" : ""}>EQ</option>

                   `;

                var e_date = ExpDates_AJAXCall(s, drpInstrumentValue);

                if (e_date && e_date.length > 0) {

                    for (var i = 0; i < e_date.length; i++)

                        if (d_exp == e_date[i].ExpDate)

                            ddl_expdate += `<option selected value="${e_date[i].ExpDate}">${e_date[i].ExpDate}</options>`;

                        else

                            ddl_expdate += `<option value="${e_date[i].ExpDate}">${e_date[i].ExpDate}</options>`;

                }

                var stk = Strikes_AJAXCall(s, drpInstrumentValue, d_exp);

                if (stk && stk.length > 0) {

                    for (var i = 0; i < stk.length; i++)

                        if (d_stk == stk[i].StrikePrice)

                            ddl_strike += `<option selected value="${stk[i].StrikePrice}">${stk[i].StrikePrice}</options>`;

                        else

                            ddl_strike += `<option value="${stk[i].StrikePrice}">${stk[i].StrikePrice}</options>`;

                }

                s_leg_data += SB_Generate_Legs_Added_HTML(b_selected, s_selected, ddl_inst, ddl_expdate,

                    ddl_strike, s_q, rowData.FuturePrice, rowData.Price, rowData.Delta, rowData.Gamma, rowData.Theta, rowData.Vega, rowData.IV);;

            });

            $(".sbnolegs").hide();

            $("#sb_groupbtns, #sb_netpremium_spread").show();

            $("#strastrategy_builder_datatable tbody").append(s_leg_data);

            SB_CalculateNetPremium();

        }

    }

    else {

        $("#perrormsg").html('');

        $("#perrormsg").html('You can add only a maximum of 10 rows');

        $("#modelpopupmsg").modal("show");

    }

    //return false;

}

And the html code return function is:-


function SB_Generate_Legs_Added_HTML(b_selected, s_selected, inst, ddl_expdate, ddl_strike, Qty, FuturePrice, Price, Delta, Gamma, Theta, Vega, IV) {

    return `<tr class="aliceBlueRow">

              <td>

                  <div class="d-inline-block ">

                      <select class="form-select border-0 analyserfields" name="sbaction" onchange="SB_Legs_Added_table_val_change('ddl',this);">

                          <option value="Buy" ${b_selected}>BUY</option>

                          <option value="Sell" ${s_selected}>Sell</option>

                      </select>

                  </div>

              </td>

              <td>

                  <select class="form-select border-0 analyserfields" name="sbinst" onchange="SB_Legs_Added_table_val_change('ddl',this);">

                      ${inst}

                  </select>

              </td>

              <td>

                  <select class="form-select border-0 analyserfields" name="sbexp" onchange="SB_Legs_Added_table_val_change('ddl',this);">

                      ${ddl_expdate}

                  </select>

              </td>

              <td>

                  <select class="form-select border-0 analyserfields" name="sbstrike" onchange="SB_Legs_Added_table_val_change('ddl',this);">

                      ${ddl_strike}

                  </select>

              </td>

              <td>

                  <div class="input-group flex-nowrap v-line pe-3">

                      <span class="input-group-text border-0"><i class="bi bi-dash textDanger pointer" onclick="SB_Legs_Added_table_minqty(${Qty},this);"></i></span>

                      <input type="text" class="form-control text-center border-0 analyserfields" name="sbqty" value=${Qty} autocomplete="off"

                          style="min-width: 40px; max-width: 80px" maxlength='6' onblur="SB_Add_Leg_QtyValue(this);" oninput="SB_calculateqtylivenetprem('qty',this);"/>

                      <span class="input-group-text border-0"><i class="bi bi-plus textSuccess pointer" onclick="SB_Legs_Added_table_maxqty(${Qty},this);"></i></span>

                  </div>

              </td>

              <td>

                  <input type="text" class="form-control border-0 analyserfields" name="sbfprice"  value=${FuturePrice}

             autocomplete="off" oninput="SB_Legs_Added_table_val_change('futprice',this);"/>

              </td>

              <td>

                  <input type="text" class="form-control border-0 analyserfields" name="sbprice"  value=${Price}

                  autocomplete="off" oninput="SB_Legs_Added_table_val_change('price',this);"/>

              </td>

              <td>

                  <input type="text" class="form-control border-0 dull-pastel-greenBG analyserfields" name="sbdelta"

                    value=${Delta}  oninput="this.value = this.value.replace(/[^0-9]/g, '')" disabled/>

              </td>

              <td>

                  <input type="text" class="form-control border-0 dull-pastel-greenBG analyserfields" name="sbgamma"

                      value=${Gamma}  oninput="this.value = this.value.replace(/[^0-9]/g, '')" disabled/>

              </td>

              <td>

                  <input type="text" class="form-control border-0 dull-pastel-greenBG analyserfields" name="svtheta"

                       value=${Theta}  oninput="this.value = this.value.replace(/[^0-9]/g, '')" disabled/>

              </td>

              <td>

                  <input type="text" class="form-control border-0 dull-pastel-greenBG analyserfields" name="sbvega"

                     value=${Vega}  oninput="this.value = this.value.replace(/[^0-9]/g, '')" disabled/>

              </td>

              <td>

                  <input type="text" class="form-control border-0 analyserfields" name="sbiv" autocomplete="off"

                      value=${IV}  oninput="SB_Legs_Added_table_val_change('iv',this);" />

              </td>

              <td>

                  <a href="javascript://" class="px-2 py-1 fs-6 analyserfields" name="sbdelete" onclick="SB_DeleteLegs(event,this)">

                      <i class="bx bxs-trash-alt text-danger"></i>

                  </a>

              </td>

             </tr>`;

}

Note:- My concept is if I click on the add button the function return SB_Generate_Legs_Added_HTML html code should append to datatable strastrategy_builder_datatable and the data is appending but if I click on the header columns the entire table data is erasing.

Suggest me where I did the mistake and how to achieve this concept.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,320 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
905 questions
{count} votes

Accepted answer
  1. XuDong Peng-MSFT 10,181 Reputation points Microsoft Vendor
    2024-05-07T08:52:40.6966667+00:00

    Hi @Ashok Kumar,

    As mentioned by AgaveJoe, it would be a better choice to use the corresponding API(DataTable.row.add()). Based on the code you provided, I did a simple test.

    Here is the code:

    <head runat="server">
        <title></title>
        <link href="Content/bootstrap.min.css" rel="stylesheet" />
        <link href="https://cdn.datatables.net/2.0.6/css/dataTables.dataTables.min.css" rel="stylesheet" />
        <script></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="sb_add" runat="server" OnClientClick="addNewRow();return false;" Text="+ ADD" CssClass="btn btn-primary w-100 w-md-auto text-center px-4" />
                <%--<button type="button" id="sb_add"  onclick="addNewRow()" value="+ ADD" class="btn btn-primary w-100 w-md-auto text-center px-4"></button>--%> 
                <table class="table table-borderless rowSpace table-round-row dtr-inline  SB_table dataTable nowrap "
                    id="strastrategy_builder_datatable" style="width: 100%;">
                    <thead>
                        <tr>
                            <th>Action</th>
                            <th>Instrument</th>
                            <th>Expiry</th>
                            <th>Strike</th>
                            <th>Qty</th>
                            <th>Future Price</th>
                            <th>Price</th>
                            <th>Delta</th>
                            <th>Gamma</th>
                            <th>Theta</th>
                            <th>Vega</th>
                            <th>IV</th>
                            <th data-dt-order="disable"></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
                <div class="sbnolegs">NO LEGS ADDED</div>
            </div>
        </form>
        <script src="Scripts/jquery-3.4.1.js"></script>
        <script src="https://cdn.datatables.net/2.0.6/js/dataTables.min.js"></script>
        <script src="Scripts/bootstrap.min.js"></script>
        <script>
            $("#strastrategy_builder_datatable").find("th").off("click.DT");
            const table =  $('#strastrategy_builder_datatable').DataTable({
                ordering: true,
                info: false,
                paging: false,
                searching: false,
                responsive: true,
                language: {
                    emptyTable: ' ',
                },
                columnDefs: [
                    {
                        width: '100px',
                        responsivePriority: 1,
                        targets: 0
                    },
                    {
                        className: 'dt-center',
                        width: '50px',
                        responsivePriority: 2,
                        targets: -1
                    },
                    {
                        width: '110px',
                        // responsivePriority: 3,
                        targets: -2
                    },
                    {
                        width: '110px',
                        responsivePriority: 4,
                        targets: -3
                    },
                    {
                        width: '110px',
                        responsivePriority: 5,
                        targets: -4
                    },
                    {
                        width: '110px',
                        responsivePriority: 6,
                        targets: -5
                    },
                    {
                        width: '110px',
                        responsivePriority: 7,
                        targets: -6
                    },
                    {
                        width: '100px',
                        responsivePriority: 8,
                        targets: -7
                    },
                    {
                        width: '100px',
                        responsivePriority: 9,
                        targets: -8
                    },
                    {
                        width: '120px',
                        responsivePriority: 10,
                        targets: -9
                    },
                    {
                        width: '120px',
                        // responsivePriority: 10,
                        targets: -10
                    },
                    {
                        width: '160px',
                        // responsivePriority: 10,
                        targets: -11
                    },
                    {
                        width: '100px',
                        // responsivePriority: 10,
                        targets: -12
                    }
                ]
            });
            $.fn.dataTable.ext.errMode = 'none';
           
            let counter = 1;
            function addNewRow() {
                table.row.add([
                        "Action" + counter,
                        "Instrument" + counter, 
                        "Expiry" + counter, 
                        "trike" + counter, 
                        "Qty" + counter, 
                        "Future Price" + counter, 
                        "Price" + counter, 
                        "Delta" + counter, 
                        "Gamma" + counter, 
                        "Theta" + counter, 
                        "Vega" + counter, 
                        "IV" + counter
                    ]).draw(false);
                counter++;
            }
        </script>
    </body>
    </html>
    

    Result:

    User's image

    Among them, you need to get the values of each field to be added as parameter in add() function, like this: [param1, param2, param3...].

    In addition, you need to prevent postback when clicking the button, you can use return false after calling the add() function or using the button and specify the type as button instead of the default "submit".

    Best regards,

    Xudong Peng


    If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful