Maintain the dropdown selection while the table is being updated

My table updates every few seconds and each row has a dropdown menu that allows users to take actions on that row.

However, the problem is that when new data is received from the database, the dropdown menu closes if it was open. This can be frustrating for users.

Initially, I had separate buttons for each action on the row, but I anticipate that the list of actions will grow, so I decided to switch to using a dropdown menu.

    <tbody ng-repeat="item in items">
        <tr>
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>
                <div class="btn-group" dropdown>
                    <button type="button" class="btn btn-sm btn-primary">Action</button>
                    <button type="button" class="btn btn-sm btn-primary" dropdown-toggle>
                        <span class="caret"></span>
                        <span class="sr-only">Split button!</span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                        <li><a>Edit</a>
                        </li>
                        <li><a href="#">Delete</a>
                        </li>
                        <li><a href="#">Something else here</a>
                        </li>
                        <li class="divider"></li>
                        <li><a href="#">Separated link</a>
                        </li>
                    </ul>
                </div>
            </td>
        </tr>
    </tbody>

I created a Plunker to demonstrate this here. It's probably easier to see than for me to explain! If you open a dropdown and wait a few seconds, you'll notice it disappears.

I would greatly appreciate any advice on this issue.

Edit: I want to thank Denocle for his helpful answer here

Also, I've made some refinements to his method without utilizing IDs in the DOM, found here

Thanks for the assistance and feedback.

Answer №1

To ensure that you can maintain the correct state of the dropdown even after refreshing, it is crucial to assign a unique ID to each row. By storing the ID of the row with the open dropdown before refreshing, you can easily locate that row once the data is updated and apply the "open" class to the btn-group on that specific row.

For a demonstration with a functional example, you can view the forked version here: http://plnkr.co/edit/6vwBnmbsJQvDxHoxLJ70

// Functions for saving and restoring the correct dropdown state

api.saveOpenBtnGroup = function() {
  this.openBtnGroupItemId = null;
  var openBtnGroup = document.getElementsByClassName('btn-group open');
  if (openBtnGroup.length > 0) {
    this.openBtnGroupItemId = openBtnGroup[0].getAttribute('data-item-id');
  }
}

api.restoreOpenBtnGroup = function() {
  if (this.openBtnGroupItemId !== null) {
    var btnGroup = document.querySelectorAll('[data-item-id="' + this.openBtnGroupItemId + '"]');
    if (btnGroup.length == 1) {
      console.log(btnGroup[0].className);
      btnGroup[0].className = btnGroup[0].className + ' open';
      console.log(btnGroup[0].className);
    }
  }
}
<!-- Assigning a unique item id to the btn-group for later retrieval -->
<div class="btn-group" dropdown data-item-id="{{item.id}}">

Answer №2

In a different approach, you can keep the dropdown open by just modifying the contents of the array instead of altering the array itself:

function updateItems() {
    $scope.i++;
    console.log("refresh");
    //$scope.items = api.getStuff();
    angular.forEach($scope.items, function(item){
      item.age = Math.floor((Math.random() * 100) + 1);
    })
}

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

Simple Express Path Challenge

I've hit a roadblock in my JavaScript tutorial on Mozilla and could really use some assistance. Below are excerpts from 3 different files: a) In the app.js file, I am trying to locate Router handlers and then present them: //app.js //the fol ...

"Encountering a problem with object transformation in Three.js using

I'm attempting to adjust both the height (Y) and vertical position of a cube simultaneously in order to keep its base on the same X-Z plane after scaling. The visual display seems to be working correctly, but the actual behavior is not meeting my expe ...

Forgetting your password with React JS

On my login page, there is a button labeled "Forget my password". When I click on this button, I want to be taken directly to the correct page for resetting my password. Currently, when I click on "forget my password", it displays beneath the login sectio ...

I'm having trouble understanding why I am not receiving any response with the "form.submit()" function inside xhr.onreadystatechange() in JavaScript/AJAX

When I try to use the form.submit() function in response to xhr.onreadystatechange, it doesn't work as expected. Below is my login form: <form action="user_home.php" method="post" id="loginForm" > <tr> <td colspan=2>Members ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

When an anchor link is dynamically created, the `click()` method does not activate the click event

After creating an anchor element using the document.createElement('a') method, I encountered an issue where the click event was not being triggered as expected. To provide more context, refer to the code snippet below: var link = document.create ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

What is the best way to send an inline SVG string to my controller?

I am trying to send an inline svg string along with some other properties to my controller. When I replace the svg string with a normal string like "blabla", it successfully reaches my controller. However, with the actual svg string, it never makes it to ...

What is the best way to save and access multiple arrays within a single object in local storage?

I am looking to streamline my code by combining 5 arrays into a single object and storing it in local storage. However, when trying to retrieve the object later on, the properties are showing up as undefined. To address this issue, I want to push an object ...

The integration of angularFileUpload seems to be malfunctioning

This question may seem simple, but I am new to using Angular. My goal is to upload images on my website using AngularFileUpload. Here is what I did when initializing my app: var app = angular.module('myApp',['ui.router'],['angular ...

View an image in advance of uploading it and concealing any broken images

The foundational code for previewing an image before it is uploaded can be found at this link. Here are the codes: <script type="text/javascript"> function readURL(input) { if (input.files && input.files[0]) { var ...

Exploring Angular.js methods to capture values from check boxes and radio buttons simultaneously

Check out my demo at https://embed.plnkr.co/R4mdZr/ Just diving into the world of Angular, I'm looking to retrieve both true values from checkboxes and radio button selections. I have a condition where if the minimum value for ingredients is one, it ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

False return - Inoperative link - Scroll option

I have a JavaScript drop-down menu that is functioning correctly, but when I click on one of the links in the dropdown, the link does not work. I suspect it has something to do with my "return false/true" setup. Here's my JavaScript code: function d ...

Add a class to alternate elements when mapping over data in React

Check out the code snippet below: <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4"> {status === "success" && delve(data, "restaurants") && data.r ...

"Create a set of arrays within an object that are duplicates four times, and then dynamically manipulate the first item within each array

Here is the layout of my array object: const foo = {"data":[ [1,'asdf'], [2,'lorem'], [3,'impsum'], [4,'test'], [5,'omg'], ]} I am looking to replicate each array four times and increment the first item ...

Tips for Sending Props While Utilizing CSS Modules

I've been working with a button component that utilizes the Tailwindcss framework and css modules for some extra styling. It currently looks like this, incorporating template literal to integrate the red background styling. CSS Module: .red { back ...

What is causing this JavaScript function to output '2'?

Recently, I came across an unusual JavaScript function: (function f(){ function f(){ return 1; } return f(); function f(){ return 2; } })(); To my surprise, it returns 2 instead of crashing the browsers as expected due to recursion. Curious ...

MUI - Material-table/core - Checkbox selection malfunctioning on click event

UPDATE : The matter also pertains to Material Ui's Data table. I attempted to replicate the issue using the provided example in the documentation but encountered the same problem. I have been struggling with an issue related to the selection feature ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...