Creating a cascading drop-down list in JSP

I am currently working on implementing two dropdown menus in my JSP. The first dropdown is for top categories and the second dropdown is for subcategories. When the JSP page loads initially, only the list of top categories will be displayed in the first dropdown while the second dropdown will remain empty. Upon selecting a top category from the first dropdown, I want the corresponding subcategories to populate the second dropdown. Fortunately, upon the initial load of the JSP page, I already have access to a databean that contains both the top category and subcategory lists. This means that when a top category is selected, I need to extract the value of the selected category and compare it with the top category list present in the databean. Then I can populate the second dropdown with the relevant subcategories. Can someone please guide me on how to achieve this? Thank you in advance. I have included my code snippet below for reference.

<div class="selectbox01">
    <select name="make" id="make" onchange="loadModel()">

        <c:forEach var="topCategory" items="${catalog.topCategories}" varStatus="status">
            <option selected="selected"></option>
            <option value="${topCategory.categoryId}"><c:out value="${topCategory.description.name}"/></option>
        </c:forEach>
    </select>
</div>
<c:set var="make" value="${WCParam.make}"/>
<div class="selectbox01">
    <select name="model" id="model">
        <option selected="selected"></option>
        <c:forEach var="topCategory" items="${catalog.topCategories}" varStatus="status">
            <c:if test="${topCategory.categoryId == make}">
                <c:forEach var="subTopCategory" items="${topCategory.subCategories}" varStatus="status2"> 
                    <option value="${subTopCategory.categoryId}">
                        <c:out value="${subTopCategory.description.name}"/></option>
               </c:forEach>
           </c:if>
         </c:forEach>
    </select>
</div>

Answer №1

To efficiently achieve this, create a JavaScript object that represents the "catalog" bean. Then, set up an onchange handler linked to the topcategories dropdown that utilizes the "catalog" object in JavaScript to retrieve the array of subcategories.

Breaking it down into steps:

Step 1: Generate a JavaScript object to represent the "catalog" bean: One method is to customize the toString() method of the Catalog bean and return a JSON object representing the bean. Alternatively, utilize the Jackson API to convert the Catalog object into a JSON string. Once done, store the JSON in a JavaScript variable. For example, in your JSP page, include the following script:

<script type="text/javascript"> var catalogJson = ${catalog};</script>

Step 2: Implement a loadModel function in JavaScript that utilizes the "catalogJson" variable to retrieve the subcategories and populate them in another dropdown.

I have omitted some details, but overall, the process should be relatively straightforward.

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

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...

Creating a PHP and MySQL powered drop-down menu that features multiple columns

I am looking to create a dropdown menu with multiple columns. The options data is retrieved from MySQL using PHP. Below is the code I have: $query = mysql_query("SELECT * FROM accounts"); <select class="form-dropdown validate[required]" style="widt ...

Achieving the new value without retrieving the old value in a jQuery on('save') event

I am currently utilizing X-editable and attempting to retrieve the value of an element when a user changes it. However, I am encountering difficulties as I am only getting the previous value instead of the changed value. For example, if the original value ...

Wix: Mobile view Lightbox reveals a hint of obscurity

On my mobile website, I needed to hide a lightbox connected to a box and have the box redirect to a different page when clicked. I implemented the code below to hide the lightbox. import wixLocation from 'wix-location'; import wixWindow from &a ...

Log4j2 generates a fresh file with a unique filename every time the JVM begins

My goal is to generate a new log file every time the JVM is started. <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <Patt ...

Verification Select Button Element

I am working on a Rails project and have implemented radio_button_tag. How can I add a validation to ensure that an option is chosen before submitting the form? <% @votes.each do |vote| %> <%= radio_button_tag "choice", "#{vote.id}" %> < ...

Guide to populating a form using a dropdown selection from a MySQL database

Hey there! I've set up a form below (entryform.php) for entering order details. The form includes fields for part_id, price, and model. Additionally, I have created connect.php to establish a connection to the database, custompcorder.php for inserting ...

Combine the initial element of one array with the initial element of another array in JavaScript

Is there a more efficient way to concatenate the first item of one array with the first item of another array in JavaScript, and automate console.log for each pair? Check out the code snippet below: $("button#search").on("click", function(){ var inputVa ...

Revamp webpage content and links without refreshing the page, similar to the navigation menu on Facebook

My website consists of two HTML pages, specifically contact.html and index.html. Additionally, there is a menu-sidebar and a content div integrated into the web design. There are two main objectives I am looking to achieve: 1. The ability to swap between ...

Dealing with undefined or null values when using ReactJS with Formik

Issue Resolved: It seems that Formik requires InitialValues to be passed even if they are not necessary. I'm currently working on a formik form in React, but every time I click the submit button, I encounter an error message stating "TypeError: Canno ...

What causes ngClick to stop working following $compile?

http://plnkr.co/edit/kL2uLPQu2vHHKIvRuLPp?p=preview Upon button click, the controller calls a service to compile HTML and inject it into the body. The compiled HTML (displaying "Hello World" from $scope.name) is referring to the scope of the controller, ...

Unlocking the power of multiple TCP connections in Java

I am facing a challenge with opening multiple TCP connections to a SIP server running on Linux. I attempted to use a simple Java client program, but was unable to exceed 350 connections from another Linux server. My goal is to establish over 50,000 connect ...

Clicking using the Actions class may result in a StaleElementReferenceException being thrown, whereas using WebElement's click

Within my testing project, there exists a static class housing various methods for handling basic interactions with WebElements. Notably, I have implemented two distinct methods for initiating a click on a WebElement. The first method utilizes the WebEleme ...

Steps for eliminating the #id from a URL page

Can someone assist me in removing or hiding my #id from the URL browser? For example: My menu1 targets "#p1" My site is "mysite.com/index.htm" When I click menu1 on my browser, it will show as "mysite.com/index.htm#p1" I want my id to not show on the U ...

AngularJS control for KendoUI Switch functionality

I have been attempting to integrate Kendo UI's switch control with AngularJS but I am encountering an issue where the value is not properly binding to the model. This is how I am implementing it: <input type="checkbox" id="locked" kendo-mobile-swi ...

Bidirectional binding of form input directive using isolated scope

Currently, I am diving deep into AngularJS and focusing on mastering directives. My goal is to create a form input directive that can be easily reused across all my forms, simplifying the repetitive markup that comes with each form. However, I am facing a ...

Navigating through routes and selecting one item from an array in real-time

In my data.js file, I have an array called 'product' containing the values 'name' and 'path'. The page URL is identified by 'path' data.js export const product = [{name:Processor, path:processor}, ...