When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form User. Users can select Caseloads from lstCaseLoad and use a button to transfer them to lstAssignedCaseLoad using client-side JavaScript. Additionally, users can also remove Caseloads from lstAssigned and move them back to lstCaseLoad on the client side. To save these changes to SQL, the user must click a submit button.

The process of adding new CaseLoads from lstCaseloads to lstAssigned and submitting is functioning properly. However, I am encountering difficulties when attempting to remove items from lstAssigned. It appears that lstAssigned becomes null during submission, preventing successful saving. Please see the code snippet below for reference:

Listboxes:

<asp:ListBox ID="lstCaseLoad" runat="server" SelectionMode="Multiple" />
<asp:ListBox ID="lstAssignedCaseLoad" runat="server" Height="175px" SelectionMode="Multiple" /> 

            //Adding Caseload to Assigned
            $("#btnAddCaseLoad").bind("click", function () {
                var options = $("[id*=lstCaseLoad] option:selected");
                $("[id*=lstAssignedCaseLoad]").append($(options).clone());

                $(options).remove();

                return false;
            });


            //Removing Caseload from Assigned
            $("#btnRemoveCaseLoad").bind("click", function () {
                var options = $("[id*=lstAssignedCaseLoad] option:selected");
                $("[id*=lstCaseLoad]").append($(options).clone());
                $(options).remove();

                return false;
            });

Code Behind

        protected void Page_Load()
        {

            if (!IsPostBack)
            {
                //Retrieving and Binding listboxes. No issues here
                GetData();
                BindData();
            }
            else
            {
                var test= Request.Form.AllKeys;
                //Temp variable to check all elements for debugging. lstAssignedCaseLoad is missing when deleting. Is fine when adding new caseload
     
          
                //Read listAssignedCaseLoad items to comma seperated strings. Becomes null when trying to remove items
                string strCaseLoad = Request.Form[lstAssignedCaseLoad.UniqueID];


                //Transfer string strCaseload to (field)List<string> for saving. Works fine when string is not empty
                userCaseLoadList = ProcessListString(strCaseLoad, lstAssignedCaseLoad);
            }
        }
        //Submit button method. Works as intended
        protected void EditUser_Click(object sender, EventArgs e)
        {
            identityMgr.EditUser(Email.Text, userRoleList, userCaseLoadList);
        }

I have tried searching for solutions but haven't been able to find an exact match for this issue. Thank you for your time and assistance!

Answer №1

The reason for this behavior is related to the "selected" attribute of options in a listbox. When you choose an option from the "lstCaseLoad" that does not have the "selected" attribute, and then click on the remove button, it will be added to the "lstAssigned" without the "selected" attribute because we are using cloning. To reverse this process, you need to select (click) the option again from the "lstAssigned" before clicking on remove. You can verify the behavior of the "selected" attribute by inspecting the options before clicking the button.

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

Conceal portion in HTML until revealed

I am attempting to create 3 sections within a single HTML file using the <section id="id"> tag, and I want to be able to open each section by clicking a link in the header with <a href="#id">1</a>, and then close it when another section i ...

You can't send headers to the client in Express after they have already been set

I successfully registered and inserted a record in my MongoDB. However, I encountered an error when trying to log in at the line "!user && res.status(401).json("Wrong User Name");" Cannot set headers after they are sent to the client at new NodeError ...

Connect data from an HTML table depending on the chosen option in a dropdown menu using AngularJS, JQuery, JSON, and

Could you please correct my errors? It's not working as I have made some mistakes. I need an HTML table based on the selection. I have tried but cannot find a solution. I created a dropdown, and if I select any value from the dropdown and click a butt ...

Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in de ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

Failing to retain hyperlinks with ajax

Currently, I am utilizing ajax to transmit data from a sophisticated custom field wysiwyg editor. Within this setup, the specific div with the class 'bio' is what I'm addressing. The issue arises when the data is retrieved - all the original ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

The iron-session package does not export the path ./next/dist from the package

I am encountering an issue while using iron-session. Below is the code snippet causing the error: import { withIronSessionSsr } from 'iron-session/next/dist'; ... export const getServerSideProps = withIronSessionSsr(async function ({ req, r ...

How can I show/hide a div based on checkbox click on my website? It works in jsFiddle, but not on my actual site. Any suggestions?

Is there a way to show or hide a div based on a checkbox click? I've got it working in jsFiddle, but for some reason, it's not functioning properly on my website. Any thoughts on how to fix this? My goal is to offer multiple payment methods (cre ...

Share a status on Facebook with an earlier date

How to Modify Facebook Post Date using Graph API facebook facebook-graph-api I am able to publish on my wall using the Graph API. By utilizing FB nod and graph, I now need to post on Facebook with a date from the past Afterwards, I can adjust the date man ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...

SwitchBase is undergoing a transformation where its unchecked state goes from uncontrolled to controlled. It is important to note that elements should not transition back and forth between un

There is a MUI checkbox I am using: <Checkbox checked={rowValues[row.id]} onChange={() => { const temp = { ...rowValues, [row.id]: !rowValues[row.id] }; setRowValues(temp); }} in ...

Executing a webservice method in an html page using javascript without the need to refresh the page

Is it possible to call a webservice from an index.html page using JavaScript? My webservice is located at "localhost/ws/service.asmx" and the specific web method I want to call is called HelloWorld. The index.html page contains an HTML submit button whic ...

Creating a dropdown menu for an extensive list of 100 menu items: a step-by-step guide

In my React JS front-end project, I have implemented a drop-down menu using Material-UI. Currently, the menu items are hardcoded which works fine for a small number of items. However, this approach becomes cumbersome when dealing with a larger number of ...

Accessing the Div id stored in a session parameter

Is there a way to store the id (div id) into a session variable? This is an example of my code below: <div class='fieldRow'>Options </div> <div id="abcde"></div> <div class='Row'> <?php $user_typ ...

Creating a versatile JavaScript library that is compatible with various platforms such as browsers, NodeJS, and single page applications like React

My question is: Is it possible to convert a basic file into a versatile library that can be utilized with Browsers (via script tag), Node JS, and Single Page Applications using a single codebase? In the past, I have primarily used existing libraries witho ...

Exploring the differences between using Node.js JSON.parse during object creation versus when utilizing a getter property

This topic primarily focuses on seeking feedback on whether the current approach is optimal or if there are better ways to handle it. If you have any advice or comments on the content below, even if not directly asked for, please feel free to share. In my ...

Building a dynamic tab menu using JavaScript: A step-by-step guide

In order to generate dynamic tab menus with JavaScript, I am seeking a solution that does not rely on jQuery as it may not be supported by all mobile devices. Any advice for replicating the same functionality using pure JavaScript would be greatly apprec ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

Approximately 20% of spoken words are not accurately conveyed by Speech Synthesis Google Voices, failing to adhere to the intended voice selection

When using speechSynthesis.speak(utterance) in Chrome with the "Google UK English Female" voice, there is an issue where a male voice is randomly spoken instead. Any thoughts on how to resolve this? Latest Update: July 26th, 2022 This appears to be a bug ...