You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Grails框架下GSP页面下拉框只读效果

How to Implement Read-Only Dropdown in Grails GSP (Create/Show Flow)

Got it, let's solve this read-only dropdown problem for your Grails create and show pages. When a user selects an option on create.gsp and submits, you want that selected value to show up on show.gsp in a dropdown that users can't modify. Here are two reliable approaches:

Approach 1: Use disabled Attribute (Simple & Straightforward)

The disabled attribute natively prevents interaction with the dropdown, and it will automatically display the pre-selected value from your domain object. Just note that disabled form elements won't submit their values if your show.gsp includes a form—so add a hidden field if you need to retain the value for submission later.

Example Code for show.gsp:

<!-- Render the dropdown with disabled state -->
<g:select 
    name="yourFieldName" 
    from="${[1, 2, 3]}" 
    value="${yourDomainInstance.yourFieldName}" 
    disabled="true" />

<!-- Optional: Add hidden field if you need to submit this value later -->
<g:hiddenField 
    name="yourFieldName" 
    value="${yourDomainInstance.yourFieldName}" />

This will gray out the dropdown and lock it to the selected value from the create page.

Approach 2: CSS + JavaScript (Keep Visual Style, Block Interaction)

If you don't want the dropdown to look "grayed out" but still need it to be unmodifiable, use this method to block user interaction while keeping the normal appearance.

Example Code for show.gsp:

<!-- Render the dropdown with a custom class -->
<g:select 
    name="yourFieldName" 
    from="${[1, 2, 3]}" 
    value="${yourDomainInstance.yourFieldName}" 
    class="read-only-dropdown" />

<!-- Add JavaScript to block interaction -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const dropdowns = document.querySelectorAll('.read-only-dropdown');
    dropdowns.forEach(dropdown => {
        // Prevent click from opening the dropdown
        dropdown.addEventListener('mousedown', e => e.preventDefault());
        // Prevent keyboard navigation/selection
        dropdown.addEventListener('keydown', e => e.preventDefault());
    });
});
</script>

<!-- Optional CSS to set a default cursor -->
<style>
.read-only-dropdown {
    cursor: default;
}
</style>

This way, the dropdown looks normal but users can't expand it or change the selected value.

Quick Notes:

  • Make sure you're correctly binding the selected value from your domain object (replace yourDomainInstance.yourFieldName with your actual domain class and property name).
  • Both methods work with Grails 3, 4, and 5—adjust the tag syntax slightly if you're on an older version, but the core logic stays the same.

内容的提问来源于stack exchange,提问作者Kosuri Naresh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:52:01