Navigation menu with nested options in the list

I have designed a dropdown menu that lists provinces, with cities mentioned under each province. My goal is to show these cities in a submenu on the left-hand side when a province is clicked.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">


<select name="campus" id="campuslocation" class="browser-default" required="">
  <optgroup label="Eastern Cape">
    <option value="31">Umtata / Mthatha</option>
    <option value="32">Willowmore</option>
    <option value="33">Willowvale</option>
  </optgroup>
  <optgroup label="Free State">
    <option value="47">Koppies</option>
    <option value="48">Kroonstad</option>
  </optgroup>
</select>

https://i.sstatic.net/YaJAC.png

Answer №1

select is not the ideal element for this task. Instead, a dropdown would be more suitable.

While there is no default method to create submenus, it can be easily achieved.

$(document).ready(function() {
  $('.dropdown-submenu a').on("click", function(e) {
    $(this).parents('ul').find('.dropdown-submenu ul').hide();
    $(this).next('ul').toggle();
    e.stopPropagation();
    e.preventDefault();
  });
});
.dropdown-submenu {
  position: relative;
}

.dropdown-submenu .dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -1px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    All South Africa
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <li class="dropdown-submenu">
      <a class="dropdown-item" href="#">Eastern Cape</a>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Umtata / Mthatha</a></li>
        <li><a class="dropdown-item" href="#">Willowmore</a></li>
        <li><a class="dropdown-item" href="#">Willowvale</a></li>
      </ul>
    </li>
    <li class="dropdown-submenu">
      <a class="dropdown-item" href="#">Free State</a>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Koppies</a></li>
        <li><a class="dropdown-item" href="#">Kroonstad</a></li>
      </ul>
    </li>
  </ul>
</div>

Answer №2

Hopefully, this solution will provide assistance. Instead of using the select element, we can utilize the list item element.

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <style>
            .dropdown-submenu {
                position: relative;
            }

            .dropdown-submenu .dropdown-menu {
                top: 0;
                left: 100%;
                margin-top: -1px;
            }

            .dropdown {
                width: 100px;
            }
        </style>
    </head>
    <body>

        <div class="container">
            <div class="dropdown">
                <button class="btn btn-default btn-lg dropdown-toggle" type="button" data-toggle="dropdown">Choose a State
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <li class="dropdown-submenu">
                        <a class="test" tabindex="-1" href="#">Eastern Cape <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a tabindex="-1" href="#">Umtata / Mthatha</a></li>
                            <li><a tabindex="-1" href="#">Willowmore</a></li>
                            <li><a tabindex="-1" href="#">Willowvale</a></li>
                        </ul>

                    </li>
                    <li class="dropdown-submenu">
                        <a class="test" tabindex="-1" href="#">Free State <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a tabindex="-1" href="#">Umtata / Mthatha</a></li>
                            <li><a tabindex="-1" href="#">Willowmore</a></li>
                            <li><a tabindex="-1" href="#">Willowvale</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>

        <script>
            $(document).ready(function(){
                $('.dropdown-submenu a.test').on("click", function(e){
                    $(this).next('ul').toggle();
                    e.stopPropagation();
                    e.preventDefault();
                });
            });
        </script>

    </body>
</html>

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

Is there a way to switch the classList between various buttons using a single JavaScript function?

I'm currently developing a straightforward add to cart container that also has the ability to toggle between different product sizes. However, I am facing difficulties in achieving this functionality without having to create separate functions for ea ...

Varied selection menu feature

Looking to build a new component: The idea is to create something similar to a dropdown list. I aim to incorporate this component into every cell (td) of table rows. The challenge lies in displaying the second div (item list) under the first div, but abov ...

Tips for eliminating corner gaps in css

As I dive into the world of CSS, I encountered an issue while working on my webpage. The problem lies in a space that appears on my displayed webpage. .grouping:before, .grouping:after { content: " "; display: table; } .grouping:after { clear: bo ...

What could be causing issues with the JQuery .Resize() function?

I'm attempting to create a responsive layout where the content div adjusts itself when the user resizes the page. The top and bottom divs are static, so only the content div changes its size based on the page flow. $(window).resize(function() { v ...

How to reduce the text input field size in Django Bootstrap for a sleeker design

I have a form with various elements like textfields, radio buttons, and text areas. The textfield size is currently too small and does not look good: https://i.sstatic.net/ghimd.png I'm wondering how I can make the textfields slightly larger and why ...

Implementing intricate inline styles in React for interactive features like hover and active states on components like buttons

I'm currently styling my buttons using the following CSS with Bootstrap. .btn-primary { background-color: #229ac8; background-image: linear-gradient(to bottom, #23a1d1, #1f90bb); background-repeat: repeat-x; border-color: #1f90bb #1f9 ...

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

What could be causing Prettier code formatter to suddenly stop formatting in VS Code?

I've been having trouble formatting my code using Prettier in VS Code. Even after reinstalling it, the issue persists and I can't seem to format my HTML/CSS code properly. The screenshot I provided shows that the code remains unformatted even aft ...

Transforming data from an HTML table into a MySQL database

Is there a way to transfer data from an HTML table created with JavaScript to a SQL database? I have been experimenting with the addRow(tableID) function but it doesn't seem to work. Any suggestions on how to solve this issue? Below is the code snipp ...

When viewing the material-ui Chip component at normal zoom, a border outlines the element, but this border disappears when zoomed in or out, regardless of

Edit I have recently discovered a solution to the unusual problem I was facing with the material-ui Chip Component. By adding the line -webkit-appearance: none; to the root div for the Chip, the issue seems to resolve itself. However, this line is being a ...

Discover the basics of incorporating libraries using npm

As a beginner in JavaScript, I am looking to incorporate moment.js or another library into my project. However, I am unsure of how to properly set up my project so that I can import from the library. Here is how I have structured my HTML: <!DOCTYPE html ...

The form transmits the URL parameter rather than executing an update

I'm having trouble with my code and can't seem to figure out why it's behaving this way. When I try to update a recordset, the page reloads upon hitting the submit button and multiple URL parameters appear in the address bar. There are two ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Using CSS to overlay text on an image on a webpage

Can anyone help me with this puzzling scenario? <TD><a href="index-1.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image20','','images/m21.jpg',1)">Home</a><img src="images/m2.jpg" nam ...

Challenges with the height of the calendar component in Vuetify

I need assistance with preventing the appearance of two scroll bars while working with Vuetify's sheet and calendar components. https://i.stack.imgur.com/yBfhj.png Below is my code snippet: <template> <v-app> <v-main> & ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

Creating a CSS image grid without relying on object-fit: cover can be achieved by

My goal is to create a horizontal masonry grid similar to Adobe Stock and Shutterstock without altering image aspect ratios by using object fit or any other stretching techniques. All the solutions I've found so far involve object-fit: cover, which c ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

Having trouble customizing a particular view within Angular

I am struggling to customize the background of a specific view in Angular. When I tried to style it with the code below, the entire view disappeared. Here is the relevant code: HTML (index.html): <div class="col-md-8 col-md-offset-2"> <div ng ...

Creating a clickable image in the header of an R Shiny app

I've been attempting to create a hyperlink from the image output, but I'm encountering difficulties despite reviewing similar questions on Stack Overflow. svg with clickable links in shiny - not clickable The tags are not working. server.r li ...