Table of Contents
ZK Combobox Dynamic Content Loading and Popup Menu Control
Problem analysis
Solution: Client Widget Customization
1. ZUL page and ZScript logic
2. Client JavaScript customization
Notes and best practices
Summarize
Home Java javaTutorial ZK Combobox keeps pop-up menu open when dynamic content is loaded

ZK Combobox keeps pop-up menu open when dynamic content is loaded

Aug 30, 2025 am 11:06 AM

ZK Combobox keeps pop-up menu open when dynamic content is loaded

This article explores the issue where ZK Combobox automatically closes when content is loaded dynamically, such as the "Show More" option, and provides a solution to prevent it from closing by overriding the doClick_() method of the client JavaScript Widget. Through this method, developers can precisely control Combobox's closing behavior and achieve more flexible user interaction, especially for scenarios where the list needs to be updated dynamically according to user selection but do not want the pop-up menu to close immediately.

ZK Combobox Dynamic Content Loading and Popup Menu Control

Combobox component in ZK Framework By default, the drop-down pop-up menu will automatically close when the user selects any item in the list. This behavior is reasonable for most single-choice scenarios, but in certain specific interactive modes, such as when a user clicks on a "Show More" option to dynamically load or switch list content, automatic closing can lead to a poor user experience because the user needs to reopen Combobox to see the updated list. This article will introduce in detail how to solve this problem through client Widget customization, so that Combobox remains open after clicking on a specific project and updates its model dynamically.

Problem analysis

When Combobox is used to implement segmented loading or toggling list views (for example, a short list with the "Show More" option, clicking to switch to the full list), its default behavior can create challenges. Combobox will be closed immediately after the user clicks on the "Show More" option, and then the user will not be able to see the full list immediately even if the backend model has been updated. You must click Combobox again to open again. This is obviously not an ideal user experience.

Many behaviors of ZK components are controlled by their corresponding client JavaScript Widget. The closing logic when a Comboitem is clicked is triggered by the doClick_() method of its client Widget. Therefore, to change this behavior, we need to customize the method.

Solution: Client Widget Customization

The core of solving this problem is to override the doClick_() method of the Comboitem client Widget. Through the zk.override mechanism, we can inject custom logic to control the shutdown behavior of Combobox without modifying the ZK core library.

1. ZUL page and ZScript logic

First, we need to define Combobox in the ZUL page and prepare different data models. At the same time, listen to user selections through the onSelect event to handle model switching on the server side.

 <zscript></zscript>

<combobox id="box" model="${model1}" readonly onselect="loadAll()"></combobox>
<script src="comboitem-doclick.js"></script>

<zscript></zscript>

Code description:

  • fullModel and model1 represent the full list and the short list, respectively. An additional "Show More" string is added in model1 as a special option.
  • The combobox component binds model1 as the initial model and sets readonly="true" to prevent users from entering at will.
  • onSelect="loadAll()" delegates the selection event to the loadAll method in ZScript.
  • The loadAll() method is responsible for determining that if the user selects "Show More", switches the combobox model to fullModel and clears the current displayed value of combobox.
  • is the key to introducing our custom JavaScript files.

2. Client JavaScript customization

Create a comboitem-doclick.js file and place it in the path accessible to the ZUL page. This file will contain logic overriding the Comboitem default doClick_() method.

 /**
 * File name: comboitem-doclick.js
 * Purpose: Keep the Combobox pop-up menu open when the user selects a specific item (such as "Show More").
 * Based on ZK version: 9.6.3 (Please verify and adjust according to the actual ZK version used)
 */
zk.afterLoad('zul.inp', function() {
    var exWidget = {}; // is used to store the original method, although in this example we do not call the original method zk.override(zul.inp.Comboitem.prototype, exWidget, {
        /**
         * Override the doClick_ method of Comboitem to control the shutdown behavior of Combobox.
         * @param {zk.Event} evt Click event object*/
        doClick_: function doClick_(evt) {
            // If Comboitem is not disabled if (!this._disabled) {
                var cb = this.parent; // Get the parent Combobox component// Call the _select method of Combobox to handle the logic of selecting items// sendOnSelect: true means triggering the onSelect event// sendOnChange: true means triggering the onChange event cb._select(this, {
                  sendOnSelect: true,
                  sendOnChange: true
                });

                // Pictures that update the hover status (if any)
                this._updateHoverImage();

                // Core logic: Decide whether to close Combobox based on the selected label
                // If the selected label is not 'Show more', close Combobox
                if (this.getLabel() != 'Show more'){
                    cb.close({
                      sendOnOpen: true, // Send onOpen event when closed (if required)
                      focus: true // Set the focus back to the Combobox input box after closing});
                }

                // Tagging Combobox should be turned off (although we control the shutdown here, keep this line for compatibility with ZK internal logic)
                cb._shallClose = true;
                // If the current focus should be retained on this component, set the focus back to the input node of Combobox if (zul.inp.InputCtrl.isPreservedFocus(this)) zk(cb.getInputNode()).focus();
                // Block the default behavior and bubbling of events, preventing repeated processing of evt.stop();
            }
        },
    });
});

Code description:

  • zk.afterLoad('zul.inp', ...): Make sure to execute our custom code after the zul.inp module is loaded, because Comboitem is defined in that module.
  • zk.override(zul.inp.Comboitem.prototype, exWidget, {...}): This is the core API customized by ZK client Widget. It allows us to override the method on the zul.inp.Comboitem prototype chain.
  • doClick_ method:
    • cb._select(this, {sendOnSelect: true, sendOnChange: true}): This line of code ensures that the normal selection logic of Combobox is executed, including triggering the onSelect and onChange events on the server side.
    • if (this.getLabel() != 'Show more') { cb.close(...) }: This is the key conditional judgment. We call the cb.close() method to close the Combobox popup menu only when the selected Comboitem tag is not "Show more". If the tag is "Show More", skip cb.close() to keep the pop-up menu open.
    • evt.stop(): prevents further propagation of events and prevents default behavior from being executed, which is very important to ensure that our custom logic takes effect.

Notes and best practices

  1. ZK Version Compatibility: The internal implementation of the client Widget may vary between different ZK versions. The above code is based on ZK version 9.6.3 and may require fine-tuning according to the ZK client API documentation if you are using another version. It is recommended to retest and verify the custom code after upgrading the ZK version.
  2. Label Matching: In JavaScript code, we use this.getLabel() != 'Show More' to determine whether to prevent closing. This means that "Show More" the string must be exactly the same as the string added to model1 in ZScript. If your Show More option is a Comboitem object, you may need to tell by other properties such as getValue() or custom properties.
  3. Dynamic model update: In the loadAll() method, box.setModel(fullModel) triggers Combobox to re-render its list. Since we prevented Combobox from shutting down, users will immediately see the updated full list.
  4. User Experience: This customization can significantly improve the user experience and avoid unnecessary interactive steps. But also make sure that the user is aware of the role of the Show More option and the fact that the list has been updated.
  5. The difference between multiple choice Combobox: The question mentions that multiple choice Combobox will not be closed. This is because the design goal of multi-select Combobox is to allow users to select multiple projects without interrupting the selection process. The doClick_() logic is essentially different from the single-select Combobox, and this solution is not directly applicable.
  6. Code Organization: It is recommended to organize all client custom code into a separate .js file and reference it in the ZUL page to keep the code neat and maintainable.

Summarize

By customizing the doClick_() method of the ZK Combobox client Comboitem Widget, we can precisely control the closing behavior of its pop-up menu. This approach is especially suitable for scenarios where content needs to be loaded dynamically (such as the "Show More" option) without wanting to close the pop-up menu immediately. Mastering ZK's client Widget customization capabilities can help developers achieve more complex and more in line with user needs, thereby building more powerful and flexible web applications.

The above is the detailed content of ZK Combobox keeps pop-up menu open when dynamic content is loaded. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to join an array of strings in Java? How to join an array of strings in Java? Aug 04, 2025 pm 12:55 PM

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

How to implement a simple TCP client in Java? How to implement a simple TCP client in Java? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

How to compare two strings in Java? How to compare two strings in Java? Aug 04, 2025 am 11:03 AM

Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.

How to send and receive messages over a WebSocket in Java How to send and receive messages over a WebSocket in Java Aug 16, 2025 am 10:36 AM

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

Correct posture for handling non-UTF-8 request encoding in Spring Boot application Correct posture for handling non-UTF-8 request encoding in Spring Boot application Aug 15, 2025 pm 12:30 PM

This article discusses the mechanism and common misunderstandings of Spring Boot applications for handling non-UTF-8 request encoding. The core lies in understanding the importance of the charset parameter in the HTTP Content-Type header, as well as the default character set processing flow of Spring Boot. By analyzing the garbled code caused by wrong testing methods, the article guides readers how to correctly simulate and test requests for different encodings, and explains that Spring Boot usually does not require complex configurations to achieve compatibility under the premise that the client correctly declares encoding.

Exploring Common Java Design Patterns with Examples Exploring Common Java Design Patterns with Examples Aug 17, 2025 am 11:54 AM

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

See all articles