What is the best way to showcase a list on a toggle-able dropdown menu, divided into groups of 5

I needed to incorporate data from my database into my navbar dropdown.

Below is the JSON data:

{
    "1": [{
        "id": 1,
        "moduleId": "1",
        "dropdownModuleName": "NL",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 17:37:21",
        "dateUpdated": null
    }, {
        "id": 2,
        "moduleId": "1",
        "dropdownModuleName": "EE",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": null,
        "dateCreated": "2018-09-19 18:01:39",
        "dateUpdated": null
    }, {
        "id": 3,
        "moduleId": "1",
        "dropdownModuleName": "SA",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": "1",
        "dateCreated": "2018-09-19 18:01:46",
        "dateUpdated": "2018-09-19 18:10:02"
    }],
    "4": [{
        "id": 4,
        "moduleId": "4",
        "dropdownModuleName": "CON",
        "isDeleted": null,
        "createdBy": null,
        "updatedBy": "1",
        "dateCreated": "2018-09-19 18:01:56",
        "dateUpdated": "2018-09-19 18:13:33"
    },{
        "id": 6,
        "moduleId": "4",
        "dropdownModuleName": "RG",
        "isDeleted": null,
        "createdBy": "1",
        "updatedBy": null,
        "dateCreated": "2018-09-19 19:13:00",
        "dateUpdated": null
    }],
}

With a script, I was able to display this data in the navbar dropdown. However, I encountered an issue where long lists made some links inaccessible on the screen.

To address this, I attempted to use chunkarray to divide the array. Unfortunately, converting the array to JSON resulted in it being displayed as a single list rather than divided chunks.

    $.ajax({
       url:'/api/navbarToggleDropdownMenu/getall',
       type:'GET',
       dataType:'JSON',
       async:false,
       success:function (res) {

           for(i in res){
              myKey = i;
              myVal = res[i]
                 for(o in myVal){
                    nKey = o 
                    nVal = myVal[o]
                    if(nVal.moduleId != undefined || nVal.moduleId != null){
                        $('[data-id="'+myKey+'"]').replaceWith('<li  class="dropdown megamenu-fw"><a href="javascript:void(0)" class="dropdown-toggle">'+nVal.moduleName+'</a>
      <ul class="dropdown-menu megamenu-content" role="menu"><li [data-div="'+myKey+'"]></li></ul></li>');

                        $('[data-div="'+myKey+'"]').append('<div class="col-menu col-md-3"><ul class="menu-col">
<li><a href="dropdownModule?id='+nVal.id+'">'+nVal.dropdownModuleName+'</a></li></ul></div>');
                      }
                 }
            }

       }
    })

The desired outcome is to display the data on the navbar by dividing the list - creating another div class="col-md-3" when the list exceeds 5 items. This ensures that each col-md-3 segment properly displays part of the list.

This is how I expect the output to be displayed:

<li class="dropdown megamenu-fw">
  <a href="javascript:void(0)" class="dropdown-toggle">Megamenu</a>
  <ul class="dropdown-menu megamenu-content" role="menu">
    <li>                               
      </div><!-- end col-3 -->  
        <div class="col-menu col-md-3">
          <ul class="menu-col">
            <li><a href="contact.html">Contact</a></li>
            <li><a href="shortcodes.html">Shortcodes</a></li>
            <li><a href="authors.html">Author</a></li>
            <li><a href="404.html">404</a></li>
            <li><a href="about-me.html">About</a></li>
          </ul>
        </div><!-- end col-3 -->
        <div class="col-menu col-md-3">
          <ul class="menu-col">
            <li><a href="contact.html">Contact</a></li>
            <li><a href="shortcodes.html">Shortcodes</a></li>
            <li><a href="authors.html">Author</a></li>
            <li><a href="404.html">404</a></li>
            <li><a href="about-me.html">About</a></li>
          </ul>
        </div><!-- end col-3 -->
      </div><!-- end row -->
    </li>
  </ul>
</li>

Answer №1

To begin, it is important to organize your data into an array and then use a counter to add the necessary open and close tags.

const exampleData = Array(28)
  .fill(0)
  .map((_, i) => `LI ${i + 1}`);

const ulSize = 5;

const openTag =
  `<div class="col-menu col-md-3">
    <ul class="menu-col">`;

const closeTag =
  ` </ul>
   </div>`;

let liCounter = 0; 
$('code').html(exampleData.reduce((c, n, i, arr) => {
  if (liCounter === 0) c.push(openTag);
  c.push(`<li><a href="#">${n}</a></li>`);
  liCounter++;
  if (liCounter === ulSize || i === arr.length - 1) {
    c.push(closeTag);
    liCounter = 0;
  }
  return c;
}, []).join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code></code>

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

Tips for adjusting text to perfectly fit within a DIV's width

I'm facing an issue where the contents in my DIV are not wrapping correctly when the width changes. Specifically, whenever the content includes a long string of characters like "______________________________________________________________" with no s ...

Expanding the padding of a span element without displacing the text inside

I'm looking to enhance a span with highlighted text, complete with some padding, while ensuring the surrounding text in the div stays put. Currently, the padding seems to work vertically (with the edge of my span overlapping lines above and below) but ...

Total sum of numerous jQuery-UI Slider values

Looking for a way to create a page with 4 jQuery-UI sliders that have a combined total limit of 400. I am open to any method of implementation, whether starting from 0 and decreasing the available total as each slider is changed, or setting one slider abo ...

Dynamic Link Generation Using jQuery

I am currently in the process of incorporating a link within a blockquote element using jQuery. At this juncture, I have developed the following code snippet: var pullQuote = $('span.pull-quote').each(function(){ var $this = $(this), hr ...

Stop Ag grid from automatically extending to the entire width of the screen

I am encountering an issue where my table scales to the full width available even when the content is limited. Take a look at the demo here: "https://plnkr.co/edit/6L8bTAwkEV6R6Be4M1Qm?p=preview" I have attempted to address this problem by settin ...

Issue with Jquery Fly To Cart Animation on Mobile Devices

On desktop view, I successfully added a 'fly to cart on click' function, but when switching to mobile view, it flies to the left side of the screen where my cart icon is not located. It essentially flies to the 'hamburger menu.' I' ...

Interact with a PHP SOAP web service using JQuery's Ajax function

I run a PHP SOAP web service that serves as a bridge to access cross-domain web services. However, I am struggling to invoke my local PHP web service methods from JavaScript (using JQuery/Ajax). Specifically, I want to call a particular method in my web se ...

Is it possible to merge two HTML selectors using jQuery?

In my HTML, I have two button elements defined as follows: <input type="button" class="button-a" value="Button a"/> <input type="button" class="button-b" value="Button b"/> When either of these buttons is clicked, I want to trigger the same ...

Scroll down navigation bar hide on scroll offset

Is there a way to prevent the navigation menu from disappearing on iOS when scrolling down due to the 'bounce' effect at the top of the page? Perhaps setting an offset for triggering the script or is there another solution? var prev = 0; var $win ...

When the user interacts with the textbox in a gridview, I want to display a checkbox list below the textbox. This can happen either through clicking

Can anyone offer advice on how to display a checkbox list below a textbox in a gridview when the user clicks or hovers over the textbox? Any tips on dealing with similar issues would be greatly appreciated. ...

What is the best way to implement a partial color filter on an image using CSS?

Looking to give our business website a fresh update, but struggling with adding a filter to the images. Our graphics designer created a mock-up for us, but I'm not sure how to implement this feature. Any help would be greatly appreciated! ...

template for login page with google closure UI design

Just starting out with google closure... are there any templates provided by Google for creating a basic user registration/login page? Most of what I've found so far seems to focus on UI manipulation and DOM creation. ...

Avoiding errors on the client side due to undefined levels in a specific response JSON can be achieved using the RESTful API

Below is a straightforward JSON response example: { "blog": { "title": "Blog", "paragraphs": [{ "title": "paragraph1", "content": "content1" }, { "title": "paragraph2", "content": "content2" }, { ...

Is an array necessary for updating only the last database record?

Requesting assistance from the PHP and SQL community as I am a novice in these areas. I have successfully created a database and implemented a form on an HTML page to update it. However, I am facing an issue where only the last record is being updated. I s ...

What is the best approach to styling a sub-child element within the first child using TailwindCSS?

Currently working with React (Next.js) and TailwindCSS. <ul> <li> <h1 className="bg-red-400">first</h1> </li> <li> <h1 className="bg-green-400">second</h1> </li> &l ...

I'm curious as to why the web browser is showing a timestamp below the image I have on my HTML page

Issue at Hand: I am currently working on coding a website that involves displaying an image. However, when the image is loaded, a timestamp appears underneath it in the web browser. Query: Could you please shed some light on why a timestamp is showing up ...

Achieving click detection on a link within an iframe in Angular 2

Is there a way to detect a click on a link within an iframe? <iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe> Inside my iframe component, I have a simple code that listens to changes in observable var ...

Guide to choosing and unchoosing a div / button using angularJs

I am attempting to create a functionality where items are displayed in a div instead of a list. When an item is clicked, the background color of the div changes and the item is added to a column. Clicking on the item again will revert it back to its origin ...

Avoid the div from covering the scrollbar within its containing parent div

Background: Trying to resolve an issue mentioned here: https://github.com/likeastore/ngDialog/issues/94 Challenge: If you open this plnkr link: http://plnkr.co/edit/qKJiNwyivqJVCAtyhwYR?p=preview and attempt to hold and drag the scrollbar with the mouse, ...

Fade the colors of the jQuery UI slider handle before it's clicked

I am looking to enhance the visibility of my vertical slider created with Jquery UI by changing its color until it is clicked for the first time. However, I am struggling to identify the correct element to modify. My attempted solution involves using the ...