"Learn the steps to include multiple g:select options in your application

Click here to download an image

Is it possible to dynamically append a combobox below the User combobox when the "ADD" button is clicked using JavaScript?

I attempted this with jQuery last night, but I couldn't get it to work properly.

<g:select name="user.id" from="${userdetailsList?.firstName}" noSelection="['':'User']"/>


<html>
    <head>
        <g:set var="entityName" value="${message(code: 'CurrencyList.label', default: 'CurrencyList')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>          
    </head>
    <body>  
    <g:if test="${flash.message}">
        <div id="userMessage" class="info" style="color:orange;background-color:#d0e4fe;">${flash.message}</div>
    </g:if>
    <table align="left">
    <tbody>
        <tr>
            <td style="font-size:20px;" colspan="3"><b>Group Add</b></td>
        </tr>
        <tr>
            <td width="70">Name</td>
            <td width="5">:</td>
            <td><g:textField name="namagrup" value="${nama}" /></td>
        </tr>
        <tr>
            <td>Description</td>
            <td>:</td>
            <td><g:textArea name="deskripsigrup" value="myValue" rows="5" cols="40"/></td>
        </tr>
        <tr></tr>

    </tbody>    
</table>
        <ol>
        <h3 >User</h3>
        <br>
        <div id="selects"><g:select name="user.id" 
                    from="${userdetailsList?.firstName}"  
                    noSelection="['':'User']" /> </div>
        <button>ADD</button>  
        <br>
        </ol>
    </body>
</html>

Answer №1

One potential solution is to implement an Ajax call to the controller, where the method will return the g.select along with all its options.

The approach outlined below should help achieve this...

Include a call to a function in the 'Add' button's onclick attribute, and within this function add...

$.ajax({
   url: "${createLink(action:'loadSelect')}",
   success: function(data, status){
       $("#selects").append(data);
   }
})

Create a div with id 'selects' so that the selects can be appended there.

<div id="selects"></div>

In your controller, add the following code...

def loadSelect(){
    // logic to fetch required data...
    render "<g:select name='user.id' from='${userdetailsList?.firstName}' noSelection='[\'\':\'User\']'/>"
}

Remember to test it out and let me know if you require further assistance

Edit: Response to your code If I understand correctly, you simply need to 'clone' the select in order to add multiple users to a group. In such cases, you don't have to make another trip to the controller or database to create a new select element.

<html>
    <head>
        <g:set var="entityName" value="${message(code: 'CurrencyList.label', default: 'CurrencyList')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>  
        <script type="text/javascript">
            function addSelect(){
                 $("#selects").append($("#firstSelect").clone());
            }
        </script>        
    </head>
    <body>  
    <g:if test="${flash.message}">
        <div id="userMessage" class="info" style="color:orange;background-color:#d0e4fe;">${flash.message}</div>
    </g:if>
    <table align="left">
    <tbody>
        <tr>
            <td style="font-size:20px;" colspan="3"><b>Group Add</b></td>
        </tr>
        <tr>
            <td width="70">Name</td>
            <td width="5">:</td>
            <td><g:textField name="namagrup" value="${nama}" /></td>
        </tr>
        <tr>
            <td>Description</td>
            <td>:</td>
            <td><g:textArea name="deskripsigrup" value="myValue" rows="5" cols="40"/></td>
        </tr>
        <tr></tr>

    </tbody>    
</table>
        <ol>
        <h3 >User</h3>
        <br>
        <div id="selects"><g:select id="firstSelect" name="user.id" 
                    from="${userdetailsList?.firstName}"  
                    noSelection="['':'User']" /> </div>
        <button onclick="addSelect()">ADD</button>  
        <br>
        </ol>
    </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

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

Adjusting mesh rotation on elliptical curve using mousewheel scrolling

I have arranged several plane meshes in a uniform manner along an elliptical curve. During the animation loop, I am moving them along the ellipse curve using curve.getPointAt with time delta and applying the matrix. Additionally, I am attempting to incor ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

Encountering a tIDENTIFIER syntax error while trying to include a button_tag in Rails

Currently, I am in the process of developing a rails application and my aim is to incorporate a button that executes a javascript onclick function. The code snippet I am using for this purpose is: <%= button_tag "Action" type: "button", onclick: "test( ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

How can I make the element.setAttribute() method function properly in Internet Explorer?

I am using JavaScript to set the style attribute of a text element with the element.setAttribute() method, giving it a name of "style" and a value of "my modifications to the style of text." While this method works well in most browsers, it is not functio ...

What is the proper way to notify a caller of a rejected call?

index.js async handleCallActions() { const tokenResponse = await this.generateTokenForChannel(this.agoraChannel); this.initializeAgoraSDK(tokenResponse.data.appID); this.joinRoomWithToken(tokenResponse.data.token, this.ag ...

Creating an array based on specific conditions being satisfied (Using Javascript)

I am struggling with a coding problem involving adding users to groups. The goal is to add each user to a group array, with a maximum of 3 users per group. If a group reaches 3 users, it should be moved to another array that collects all the groups. I then ...

Loading images ahead of time - JQuery

Currently, I am utilizing a Kinetic.Layer to import images into a canvas. One issue I am encountering is when I click a print button, it retrieves images from another file and presents them on a white page for printing. The first image consistently loads, ...

Instant data entry upon clicking

In an attempt to automate input based on image pairs, I encountered a challenge. On one side, there are two images that need to be matched with input fields, and on the other side, there are corresponding letters for each image to fill in the inputs upon c ...

We are experiencing a peculiar issue with the camera functionality in ThreeJS

I have created a scene in ThreeJS featuring two cubes, a camera, a light, and a plane. The cubes rest on the plane while the camera gracefully circles around the green cube. Despite my efforts, I am encountering an unusual issue with the camera angles. As ...

Calculating the sum of all textboxes with jQuery

I'm encountering an issue when trying to add the values of textboxes on blur call. Specifically, after entering a number in one of the textboxes, it throws NaN when attempting to sum up the values from other textboxes. Below is the code snippet causi ...

Is it possible to utilize various return values generated by a regex?

Working on a project where I am utilizing regex to extract links from a Google Calendar XML feed. The links appear in the following format: <a href="http://www.drsketchysdublin.com/event-registration/?ee=11">http://www.drsketchysdublin.com/event-reg ...

Ember.js encountering an "Access-Control-Allow-Origin" error with Ajax

Seeking opinions on how to resolve the Access-Control-Allow-Origin issue in this simple Ajax code snippet. Attempts to define the Ember "Access-Control-Allow-Origin": "* " have been unsuccessful. Has anyone with a similar problem found a solution? The URL ...

Media queries in JavaScript allow developers to adjust the styling

I'm facing an issue with reducing the size of a cube on smaller screens using media queries. I have implemented media queries in JavaScript because my cube size is defined in JS. However, the cube size remains the same even when I resize the browser w ...

What could be the reason for my jQuery script not functioning properly on my web form that was inherited from a MasterPage?

In the head of my master page, I have included: <script src="Script/jquery.min.js"></script> <link href="Stylesheet/Master.css" rel="stylesheet" /> My webform (Login.aspx) inherits from this master page, and in Login.aspx I have: <a ...

The React Router onEnter Function Error: "Maximum call stack size exceeded"

I'm currently checking if a specific configuration value is set, and if it is, I want to redirect to a child route. If not, the page should display as usual. However, when I implement this code, the URL updates as expected but then seems to get stuck ...

Having trouble getting the Random Function to function correctly in Discord.js

I'm working on a piece of code that generates a random value to select two different values from two separate arrays. Every time I run it, however, the result seems to be the same and not truly random. I'm not sure where I went wrong with this. I ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

How to use JavaScript to Hide the Chrome Print Preview Dialogue Box

Is there a way to close the print preview dialogue box opened by the window.print() method using JavaScript? I'm thinking about using Custom Events to dispatch the "esc key", but I'm not sure where to dispatch it on the element. https://i.sstat ...