DataTable values are getting the default values (initiallyloadedvalues) when we click on the dropdow

DataTable values are getting the default values (initiallyloadedvalues) when we click on the dropdow

Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

I'm very new to this DataTable logic implementation concept and I have append the data to the DataTable and in that DataTable controls I have written some event logic (ex: dropdown onchange and textbox oninput events) and those events are firing successfully and values are changing on other controls as well but I'm facing an issue , that is the changed values are not persisting properly to those controls (based on the screen size the DataTable is auto adjusting to the screen and at that time the small dropdown is coming if I click on that the hidden controls are coming but values are not coming properly )

For more info please click this url https://stackoverflow.com/questions/78776119/datatable-values-are-getting-the-default-values-initially-loaded-values-when-w for better knowledge(detailed info).

Sorry for my bad English.

Please help me.

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin

    Hi,

    I'm happy to take a look at a test case showing the issue and try to help debug that.

    Allan

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @allan thanks for your comment if anything required will provide

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    if anything required will provide

    Allan asked for a running test case that shows the issue so we can help debug..
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @allan any update on this issue?

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    The next steps are yours. Allan asked for a running test case showing the issue to help debug. Debugging code snippets is usually difficult unless there is something obvious. Start with this template to create the test case:
    https://live.datatables.net/

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @kthorngren thanks for your comment and will create the test case

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @allan and @kthorngren this is the test case of my logic https://live.datatables.net/mogarine/119/edit

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    But in this text case I'm unable to explain my scenario because here only coming the data table as web response but not as mobile or based on the system compatibility means auto adjust the columns as I mentioned my blog {You can check my explanation and my images}

    https://stackoverflow.com/questions/78776119/datatable-values-are-getting-the-default-values-initially-loaded-values-when-w

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    Are you saying that the problem occurs with Responsive hidden columns? I added the Responsive extension to your test case:
    https://live.datatables.net/mogarine/120/edit

    Please provide the steps to replicate the issue and the expectations of what should happen instead.

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Are you saying that the problem occurs with Responsive hidden columns?

    Yes.

    Will create the test case ASAP.

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @allan and @kthorngren ,

    I've created a test case, which you can view here:

    https://live.datatables.net/mogarine/144/edit

    In this scenario, I'm facing an issue where the values are not persisting correctly in the DataTable.

    For example, when I change the IV value using the oninput event, the corresponding values update as expected. However, if I expand and collapse the row using the arrow (up/down), the values reset to their previous state instead of retaining the updated ones.

    I hope this clarifies the problem I'm encountering. Any assistance would be greatly appreciated as I'm quite new to working with DataTable integration.

    Please help.

    Thank you!

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949
    edited July 31

    There are a couple issues:

    1. You are initializing the Datatable, using rows.add() to add the rows, destroying the Datatable then initializing with the settings you want. Instead you should initialize with the settings you want then add the rows. See this updated test case: https://live.datatables.net/pinojuvo/1/edit
    2. You are directly updating the HTML with new values. Datatables doesn't know about these changes. See this FAQ. I would consider using row().data() to update the row data and columns.render to generate the input HTML for each cell. See this example.

    Here is a simple example:
    https://live.datatables.net/wihoxodu/1/edit

    Update the text input with the value 9 (something not in the table). In your test case after making a change try to search for an updated value which will filter all the rows. Search for 9 in my example and the search works.

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @kthorngren,

    I understand that you're trying to help me with redrawing the table data and staying on the page. However, my issue specifically involves Responsive column values not persisting correctly. In your example, the table is a direct (web view) table, where I'm not encountering any problems.

    Could you please provide an example that demonstrates how to persist Responsive column values in the table after a redraw?

    If you're able to modify my code to address this, that would be a huge help.

    Thank you for your patience with me.

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949
    edited August 1

    However, my issue specifically involves Responsive column values not persisting correctly.

    Just add responsive to the solution to see that my example will persist the updates.

    Could you please provide an example that demonstrates how to persist Responsive column values in the table after a redraw?

    I updated my example to show this:
    https://live.datatables.net/wihoxodu/2/edit

    Update the Position column and the example will update the salary column with the same value. You will see the Salary value remains updated whether the child row is open or closed or if the Salary column is not hidden via responsive.

    As I said you need to use Datatables API's to update the values otherwise Datatables data cache won't have the updates. My example demonstrates how to do this regardless of using Responsive.

    If you're able to modify my code to address this, that would be a huge help.

    You have a lot of code in the test case and it would take time to understand what you are doing and to modify to work. My example should show you what to do. If you have specific questions we can help.

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @kthorngren,

    I understand that my initial code was complex and might have taken some time to grasp. To simplify things, I've created two separate test cases:

    First Test Case:

    I've created an empty scenario where I've removed my logic code for clarity. You can view it here:

    https://live.datatables.net/mogarine/162/edit

    Second Test Case:

    https://live.datatables.net/mogarine/167/edit

    In this scenario, I've kept only the oninput change event logic for the textboxes with types 'iv', 'futprice', or 'price'.

    Here's how I'm checking the field's position, whether it's in the parent row or the child row:

    //Parent row find:
    let parentRow = $(tt).closest('tr.dt-hasChild');
    let childRow = parentRow.nextAll('tr.child').first();

    //Child row find:
    let childRow_1 = $(tt).closest('tr.child');
    let parentRow_1 = childRow_1.prevAll('tr.dt-hasChild').first();

    Based on this, I wrote if and else if conditions to identify the fields:

    if (parentRow.length && childRow.length && (type === 'iv' || type === 'futprice' || type === 'price'))

    else if (childRow_1.length && parentRow_1.length && (type === 'iv' || type === 'futprice' || type === 'price'))

    Then, I assign values to the corresponding fields.

    I believe my approach might not be entirely correct, so I would appreciate your help in refining my code.

    Thank you for your patience with me.

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949
    edited August 1

    Sorry but your test case is still complex to follow the code to update with a working example. I updated your test case with a simple example:
    https://live.datatables.net/mogarine/168/edit

    I removed the first Datatable initialization, as described above:

    //     $("#strastrategy_builder_datatable").DataTable().destroy();
    //     var table = $('#strastrategy_builder_datatable').DataTable({});
    

    I moved the row.add() after the second initialization and populated the price and delta fields with the raw values.

        table.row
            .add([
                action,
                ddl_i,
                ddl_e,
                ddl_s,
                q,
                f,
                '4567.55',
                '4567.77',
                g,
                t,
                v,
                iv,
                dlt,
            ]).draw(false);
    

    I used columns.render to render the inputs for the price and delta fields:

        {
          targets: 6,
          render: function (data, type, row) {
            if (type === 'display') {
              return `<input type="text" class="form-control border-0 analyserfields whiteBG" name="sbprice" style="min-width: 90px;" maxlength="9" value=${data}
                      autocomplete="off" oninput="SB_Legs_Added_table_val_change('price',this);"/>`;
            }
            return data;
          }
                },
                {
          targets: 7,
          render: function (data, type, row) {
            if (type === 'display') {
              return ` <input type="text" class="form-control border-0 dull-pastel-greenBG analyserfields whiteBG" style="min-width: 90px;" maxlength="7" name="sbdelta"
                        value=${data}  oninput="this.value = this.value.replace(/[^0-9]/g, '')" disabled/>`;
            }
            return data;
          }
        },
    

    Note the use of ${data} in the render function to get the raw value instead of using ${price}.

    I commented out most of the code in SB_Legs_Added_table_val_change() so it wouldn't conflict with using the Datatables API to update the row data. I commented each line in the function that I added.

    Using this solution will eliminate the need to use jQuery to find the input in the parent or child and using jQuery to update the appropriation fields. Basically get the row data into a Javascript variable, update the variable then assign it back to the Datatables data cache.

    To test it update the Price column. The function will update the Datatables cache with the price value and will set a random number for the delta value to simulate a calculation your code might perform to update multiple fields. Thee values are persisted.

    You may want to use a change event instead of input event. You might be able to make the input elements more generic to apply the same input to multiple columns and create a delegated event handler instead of a DOM event defined on the element. Like my example:
    https://live.datatables.net/wihoxodu/2/edit

    Also see this example of defining events with Datatables.

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @kthorngren,

    I’ve modified my code according to your suggestion, and it’s working well. However, I'm having trouble persisting dropdown values in the DataTable in the same way that you’ve shown for persisting price and delta values upon redraw. Could you please provide an example of how to persist dropdown values in the DataTable? I’ve attempted this myself, but haven’t been able to get it working correctly.

    My entire code is based on DataTables, with different concepts implemented throughout, all of which are crucial.

    The DataTable works fine on the web (desktop) version since there are no issues with Responsive hidden columns. However, I’m facing significant issues in the mobile responsive view, and I have a few more questions about handling Responsive hidden columns.

    1. For example, if I have a refresh button and click it to update the DataTable rows, how can I find the index of the table columns and update the values accordingly?

    2. When I click the Submit button, I need to retrieve the values of the DataTable columns for all rows. How can I achieve this?

    Thank you for your patience. If you could clarify these doubts, it would be a great help to me.

    Thank you!

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    Could you please provide an example of how to persist dropdown values in the DataTable?

    That is a bit more complex. My understanding of responsive is it moves the HTML elements to the child row. The selected option is not, by default, kept track of in the document. The only option I can think of to work with responsive is to add selected to the appropriate option element, like this:

    <option value="CE">CE</option>
    <option value="PE" selected>PE</option>
    <option value="FUT">FUT</option>
    <option value="EQ">EQ</option>
    

    This has the PE option as selected. Use columns.render to generate the select list and set the appropriate option with the selected text, for example:

          render: function (data, type, row) {
            if (type === 'display') {
              // Remvoe current `selected` and reapply to selected option
              inst = inst.replace(' selected', '').replace('"' + data + '"', '"' + data + '" selected');
              return `  <select class="form-select border-0 analyserfields whiteBG" style="min-width: 80px;" name="sbinst" onchange="SB_Legs_Added_table_val_change('ddl',this);">
                          ${inst}
                      </select>`;
            }
            return data;
          }
    

    Keep the cells with the select lists updated with the raw data like the text inputs:

      if (type === 'ddl') {
         // Update Datatbles cache with newly selected option
        data[1] = val;
    
        // Update the Datatables data cache and redraw the Datatable
        row.data( data ).draw(false); 
    
        // Show updated select HTML
        console.log( table.cell( row, 1 ).render('display') )
         
      }
    

    Updated test case:
    https://live.datatables.net/mogarine/172/edit

    For example, if I have a refresh button and click it to update the DataTable rows, how can I find the index of the table columns and update the values accordingly?

    I'm not sure I understand the question. Use row().data() to fetch the entire row's data or use cell().data() to get a particular cell's data in the row - see an example of this in the above console.log statement, specifically cell( row, 1 ) gets the 2nd cell in the clicked row. Use the same API's to set the data.

    Maybe you are referring to data[1], for example, when using arrays. If you use objects instead its easier to define the data element to get or set. See the data docs for details.

    Please provide more detail or a simple test case showing the issue you are trying to solve.

    When I click the Submit button, I need to retrieve the values of the DataTable columns for all rows. How can I achieve this?

    Use rows().data() to get all the table data. Possibly you will want to chain toArray() to convert the result to a Javascript array.

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @kthorngren, I'll respond after I've updated the logic across my project where I'm using the DataTable concept.

    For example, if I have a refresh button that updates the DataTable rows, how can I identify the column indices and update the values accordingly?

    For this:-

    I'm not sure I understand the question.

    My explanation scenario:-

    To clarify, my question is: When I click the refresh button, I want the DataTable to update with the latest values I retrieve from the service. These updated values should be correctly persisted in the table according to our established concept.

    I really appreciate your patience and am very thankful for the great answers and solutions you've provided.

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    Depends on how you are initially loading the table. Here arae some options:

    1. If using ajax then use ajax.reload() to refresh the Datatable.
    2. If using rows.add(), like your test case, then use clear() to clear the table before using rows.add().
    3. If using DOM sourced table then use destroy() followed by jQuery empty() to clear the table (see the example in the docs), populate the HTML table and reinitialize Datatables.

    Kevin

  • Kumar007Kumar007 Posts: 13Questions: 1Answers: 0

    Hi @kthorngren, I've encountered an issue where, when adding more than one row to the DataTable, the text from the textbox control appears in the input field.

    You can check this test case here:

    https://live.datatables.net/mogarine/178/edit

    In this test case, I've added the following code:

    for (var i = 0; i < 3; i++) SB_Generate_Legs_Added_HTML(ddl_bs,inst,ddl_expdate,ddl_strike,Qty, FuturePrice, Price, Delta, Gamma, Theta, Vega, IV, typeclick);
    I'm not sure why this issue is happening. Any insights?

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    Its due to initializing the Datatable adding one row, destroying (which leaves the added row in the HTML), reinitializing the Datatable and adding a new row. The first row is now the generated HTML instead of the raw data.

    Use DataTable.isDataTable() to see if the Datatables is initialized. If it is then skip reinitializing. Updated test case:
    https://live.datatables.net/mogarine/179/edit

    Kevin

Sign In or Register to comment.