Tips for preserving the toggle state of a table row using JQuery when an aspx page undergoes postback?

Struggling with JQuery to toggle open/close three table rows in a asp.net web form page, I have managed to use the scripts provided below. However, whenever I click on the "Submit" button causing a postback, the opened table rows close and the page reverts to its initial state. Is there a way to preserve the open table row state after the postback?

(this code utilizes jquery-2.2.4.js and font-awesome 4.7.0)

  1. JQuery script:

<script type="text/javascript">
    $(function () {
        var $table = $("table");
        $table.find(".activator").click(function () {
            $(this).toggleClass("open");
        });
    });
</script>
  1. CSS class:

    .filterTable {margin: auto; border: 0px solid #808080;} .activator {cursor: pointer;} .activator.open, .activator:hover {background: #f8f3ba; border:1px dashed #808080} .activator.open .fa-plus-square-o, .activator .fa-minus-square-o, .activator + .hidden-row {display: none;} .activator.open + .hidden-row {display: table-row;} .activator.open .fa-minus-square-o {display: inline-block;}

  2. HTML code:

    <div>
        <table class="filterTable">
          <tbody>
            <tr class="activator">
              <td><i class="fa fa-plus-square-o"></i><i class="fa fa-minus-square-o"></i> Row 1</td>
            </tr>
            <tr class="hidden-row">
              <td>Row 1 content<br /> - row 1</td>
            </tr>
            <tr class="activator">
              <td><i class="fa fa-plus-square-o"></i><i class="fa fa-minus-square-o"></i> Row 2</td>
            </tr>
            <tr class="hidden-row">
              <td>Row 2 content<br /> - row 2</td>
            </tr>
            <tr class="activator">
              <td><i class="fa fa-plus-square-o"></i><i class="fa fa-minus-square-o"></i> Row 3</td>
            </tr>
            <tr class="hidden-row">
              <td>Row 3 content<br /> - row 3</td>
            </tr>
           </tbody>
        </table>
        <div style="height:30px;"></div>
        <asp:Button ID="Button1" Text="Submit" runat="server" CssClass="btn btn-primary" />
    </div>
    

Image a - initial page:

image of the initial state of page

Image b - toggled opened (when postback this state cannot maintain)

image of the table-row expanded state of page, which will not maintain after postback

Answer №1

To ensure a javascript function is executed after a postback on an aspx page, you can utilize the following approach:

function pageLoad(){
alert('This message will pop up after each postback')
// This function will trigger after every postback 
// You can set the row state in a hidden field upon clicking a table row, and then check the hidden field value to toggle the rows postback
}

Answer №2

If you want to remember the expanded row's index even after refreshing the page, you can utilize the power of localStorage. By storing and retrieving the index value from localStorage, you can easily toggle the desired class when needed. Here is a simple example demonstrating how to achieve this:

<script type="text/javascript>

    function storeIndex(index){
       let localStorageArray = JSON.parse(localStorage.getItem('expandedRowIndex'));
       if(!localStorageArray){
          localStorageArray = [];
       }

       if(!localStorageArray.includes(index)){
          localStorageArray.push(index)
       }

       localStorage.setItem('expandedRowIndex',JSON.stringify(localStorageArray))


    }

    function removeIndex(index){
       let localStorageArray = JSON.parse(localStorage.getItem('expandedRowIndex'));

       if(localStorageArray){
          localStorageArray = localStorageArray.filter(i => i !== index);
          localStorage.setItem('expandedRowIndex',JSON.stringify(localStorageArray))
       }
    }

    $(function () {
        var $table = $("table");
        $table.find(".activator").click(function () {
            $(this).toggleClass("open");

            const index = $(this).index('.activator')
            if($(this).hasClass("open")){
               storeIndex(index)
            }else{
               removeIndex(index)
            }
        });

        // Read stored index
        const localStorageArray = JSON.parse(localStorage.getItem('expandedRowIndex'));

        if(localStorageArray){
            localStorageArray.foreach((index) => {
                $table.find('.activator').eq(index).toggleClass("open");
            })
        }
    });
</script>

This method has not been tested yet, but it should work seamlessly. Give it a try and see if it meets your requirements. Good luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of jQuery autocomplete paired with getJSON

I am trying to implement the jquery autocomplete plugin in combination with the jquery GetJson function on my client page. Here is what I have so far: <script> $(document).ready(function () { var test; $.getJSON ...

Questions and Answers - Expand/Collapse Feature for Accordions

I am currently working on enhancing an existing "FAQ" accordion page by implementing the expand/collapse feature to function seamlessly. I have successfully set up the page to begin with all sections collapsed, however, I am facing an issue where clicking ...

Personalize the File upload with HTML and Javascript

https://jsfiddle.net/yugxqopz/ I'm new to the world of UI and have a simple request: 1) I want to upload a document using an "attach file" option 2) Once the file is selected, I want to automatically trigger a specific JavaScript function as shown ...

Does "th:each" assign all attributes to the same column?

Having an issue where the "openhours" from the database are loaded into a view, but all 7 opening hours are listed in the Monday column. Below is the code snippet: (HTML) <div class="table-hover"> <table class="table table-striped table ...

Transforming data from the HttpRequest.QueryString into an array of objects

I have been attempting to convert the data from an HttpRequest.QueryString into an array of objects using the following custom extension method: public static object[] ToObjectArray(this NameValueCollection nvc) { var ret = new object[nvc.Count]; ...

Attempting to replace jquery ajax functionality with pure JavaScript fetch. Utilizing fetch to retrieve the response body

There is a challenge in transitioning from a jQuery AJAX script to using fetch in a Laravel site. The issue arises when trying to pass parameters like quantity and product type in the body of a GET request using fetch. Despite changing the body parameter t ...

Struggling with implementing jquery Ajax and a php script to fetch information from a mysql database

I'm encountering issues with my current web app project in displaying a simple jpg image based on the selected radio button using jQuery AJAX along with a PHP script to interact with MySQL. Below is my ajax.js file: $('#selection').change( ...

Unable to activate transition-delay property when switching classes

I have a scenario where I am using jQuery to add and remove a class from the parent element (body). However, I noticed that the transition-delay property seems to be behaving differently in different browsers. It works fine in Safari but breaks in Chrome a ...

Ways of retrieving data from a JSON file using JavaScript on a local system

My Python program generates an html page for displaying results. The html file, tables.js (to handle dynamic table operations), and data.json are saved in the output directory on disk. The JSON file contains data from the Python run that I need to access u ...

Defining a Global Variable using the jQuery $(this)

I have been looking for ways to simplify my coding process, and one method I've tried is assigning a global variable. var parent = $(this).parent().parent().parent(); var parentModule = $(this).parent().parent().parent().parent(); Throughout my code ...

Automatically populating and submitting a form after receiving search results via ajax

I have been struggling with this issue for a few days now and could really use some help from the experts here. I am new to sql, javascript, jquery, ajax, css, and php. Although I studied Computer Science in college 15 years ago, I seem to be missing some ...

Tips on keeping these elements centered

I'm having trouble keeping these blocks of code centered. Can someone help me out? Here's the code snippet: main { width: 70%; float: left; clear: both; border- ...

Utilizing JavaScript and the Document Object Model (DOM) to display images within a

My main goal is to have images load dynamically as the background of the browser frame, without any white spaces or repeats. I've successfully achieved this statically, but now I want to implement it so that different images are generated randomly. W ...

In what way are WCAG guidelines 1.4.3 Contrast (Minimum) and 1.4.11 Non-text Contrast connected to the text within user interface elements?

WCAG 2.1 brought in success criterion 1.4.11 Non-text Contrast to address UI components like checkboxes, sliders, and more. Is it permissible to overlook 1.4.11 for the background color of a button if the text inside provides sufficient contrast, as manda ...

Having trouble adjusting the image size in the Semantic UI Feed Summary component

Currently experimenting with the example code to expand my knowledge of Semantic UI. The Feed view caught my eye, but I am interested in adding another avatar/mini image at the end of my summary line. While I can successfully insert the additional image, I ...

Can someone explain the purpose of adding "v=747" at the end of /site_media/base.css?v=747?

Observing a webpage's source code, I came across the following CSS declaration in the header: <link rel="stylesheet" href="/site_media/base.css?v=747" /> Could you please explain the significance of "?v=747" at the end of this CSS declaration? ...

Having trouble with your Bootstrap 4 Dropdown Menu?

I attempted to implement the dropdown menu example from Bootstrap 4, but unfortunately it does not seem to be working as expected. The dropdown menu does not appear when clicked. <li class="nav-item dropdown"> <a class="nav-link dropdown-to ...

Clicking on a link to reveal the nearest <OL> list items

Among my multiple definition lists are nested ordered lists and anchors. When clicked, I aim to retrieve the relevant list items. Can someone confirm if the code below is the correct approach? Appreciate it. <dl> <dt><a href="/">Colors ...

Troubleshooting layout problems caused by positioning items at window height with CSS and jQuery

At this moment, my approach involves utilizing jQuery to position specific elements in relation to the window's size. While this method is effective when the window is at its full size, it encounters issues when dealing with a debugger that's ope ...

What is the best way to generate a new CSRF token in LARAVEL using ajax?

My form contains numerous fields and allows users to add an unlimited number of additional fields. However, if a user takes too long to fill out the form, the CSRF token expires, resulting in a "CSRF token mismatch" error when they submit it using LARAV ...