Press on the menu <li> item to create additional submenus

A group of friends is facing a challenge. They want to create a dropdown sub-menu that appears directly below the selected item when clicking on a link from a menu.

So far, they have been able to use ajax to send requests and generate a sub-menu. However, they are struggling because the sub-menu always shows up in the first position:

Below is the HTML CODE for their simple menu:

<ul>
   <li><a href="#" data-id="1" class="region_id">Item 1</a>
   <ul id="city"></ul>
   </li>
   <li><a href="#" data-id="2" class="region_id">Item 2</a>
   <ul id="city"></ul>
   </li>
   <li><a href="#" data-id="3" class="region_id">Item 3</a>
   <ul id="city"></ul>
   </li>
   <li><a href="#" data-id="4" class="region_id">Item 4</a>
   <ul id="city"></ul>
   </li>
   <li><a href="#" data-id="5" class="region_id">Item 5</a>
   <ul id="city"></ul>
   </li>
</ul>

The JavaScript code they have implemented is as follows:

$('.region_id').on('click', function(event) {
    event.preventDefault();

    $.get('{!! url("filter_city") !!}', {id : $(this).attr('data-id'), token: $('input[name="_token"]').val() }, function(data) {

       var cities = $('#city');
        cities.empty();

        $.each(data, function(key, value) {
          cities.append($("<li></li>").text(value)); 
        });

    });
});

This is the result they are currently getting when clicking any option:

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

The friends are looking for advice on how to achieve the desired outcome. Greetings from Chile!

Answer №1

It's important for identifiers in HTML to be unique. To achieve this, you can assign a common class and then navigate the DOM using various methods.

For instance, instead of using an ID, you can utilize city as a CSS class. Subsequently, you can pinpoint the relevant element utilizing any of these techniques:

var cities = $(this).next('.city');
//var cities = $(this).siblings('.city');
//var cities = $(this).closest('li').find('.city');

HTML

<ul>
   <li>
        <a href="#" data-id="1" class="region_id">Item 1</a>
        <ul class="city"></ul>
   </li>
</ul>

Script

$('.region_id').on('click', function(event) {
    event.preventDefault();
    var cities = $(this).next('.city');

    $.get('{!! url("filter_city") !!}', 
        {
            id : $(this).data('id'), 
            token: $('input[name="_token"]').val() 
        }, 
        function(data) {       
            cities.empty();
            $.each(data, function(key, value) {
              cities.append($("<li></li>").text(value)); 
            });
        }
    );
});

It is advisable to utilize .data() instead of attr() when retrieving custom attribute values like data-*.

var id = $(this).data('id');

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

Incorporating AJAX functionality into an existing PHP form

I am currently working on a PHP registration form that validates user inputs using $_POST[] requests. Validating username length (3-20 characters) Checking username availability Ensuring the username matches /^[A-Za-z0-9_]+$/ pattern and more... Instead ...

"TailwindCSS opts for the inclusion of prefexied utilities instead of relying

Trying to set the height of the div to h-2, with a class that includes height animation on medium devices. The issue is that even though h-2 should be used on mobile, tailwindcss still uses h-20 instead. Any thoughts on why this may be happening? Here i ...

Issue with jQuery .css() function malfunction in Internet Explorer

While trying to enhance my website, I experimented with the Add class method $("select[name='" + ABC+ i + "']").addClass('addBorder'); To my disappointment, it worked smoothly in Chrome, FF, and Safari but failed in IE. So I decided ...

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

The background image will expand to fill any available space

I'm currently working on rendering divs with a background image CSS property. The images have fixed sizes, and I want to display them in a grid layout. However, the divs with background images stretch when there is extra space available, which is not ...

The issue with jspdf is that it is failing to generate PDF documents of

I'm currently developing a resume builder app using ReactJS. One of the functionalities I'm working on is enabling users to download their resumes as PDFs. However, I've encountered an issue with the generated PDFs when using jsPDF. The down ...

Avoid triggering the onClick event on multiple submit buttons when the form data is deemed invalid by vee-validate

How can I ensure that the onClick event on a button is only called if certain input fields are valid, using vee-validate ValidationObserver? The validation should apply to individual buttons within a form, rather than the entire form itself, as there are m ...

What is preventing the direct passing of the dispatch function from a useState hook into an onClick handler function?

const Counter = () => { const [count, setCount] = useState(0); // Uncommenting the line below would result in an infinite loop because it directly invokes setCount(count + 1) on render. // This causes the component to continuously re-render and up ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Issue with fixed positioning on iPad devices

A unique feature we implemented on our site is a small control that is positioned at the bottom of the screen. However, upon viewing the site on an iPad, the control does not stay fixed at the bottom but rather floats in the middle. What's the issue ...

Unable to retrieve information from the wiki API

Here is the link to my codepen project: https://codepen.io/mlestina/pen/OZpOQW?editors=1111 I am having trouble retrieving data from the Wiki API. When I check the Contr-Shift-J readout, I see: Loading failed for the <script> with source “https: ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

Looking to enlarge a few CSS classes, but unsure of the best approach

My app has some CSS code that I found, but it's too small. Can anyone help me increase the size by 150%? I am using React-Bootstrap for styling, so I'm looking for a way to enlarge the element without adjusting every attribute in the CSS classes. ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Simple steps to turn off error highlighting for TypeScript code in Visual Studio Code

Hey there! I've encountered an issue with vscode where it highlights valid code in red when using the union operator '??' or optional chaining '?.'. The code still builds without errors, but vscode displays a hover error message st ...

What causes the size of text to change when I zoom in my browser?

As I work on my website, I am facing a challenge with maintaining consistent text size as the page scales. For example: p { width: 10%; height: 10%; background-color: rgb(0,0,0); top: 50%; left: 50%; position: fixed; color: rgb(255,255,25 ...

Creating a Click Counter with jQuery 2.0.1/2.0.2: A Step-by-Step Guide

Currently in the process of creating a fundraising webpage for charity, I have chosen to display an animated rabbit making its way Around The World. My progress so far includes a non-looping gif that plays on click, with a limitation on how often it can b ...

Product pages created with PHP, such as displaying as: Page: [1] 2 3 4

I am working on a product page created with WordPress that fetches products and displays them. However, I want to restrict the number of products visible at once. Code for generating with WordPress/PHP: $pages = get_pages(array('parent' => $ ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...