Move items from one list to another using JavaScript

In my scenario, I have a userlist that is populated from a database. Below is the implementation of the Userlist:

<select id="Userlist" name="cars" runat="server" multiple="true" style="width: 270px; height: 200px;">
</select>

The objective is to transfer selected items from the Userlist to another list called ToChoose. Here's how ToChoose is defined:

<select id="ToChoose" name="cars" multiple="multiple" style="width: 270px; height: 200px;"></select>

<input id="ButtonAddUsers" onclick="return validateUser();" type="button" value="Add" />

Below are two JavaScript functions that I attempted to make this functionality work:

function validateUser() {
            var selItem = document.getElementById("Userlist").selectedIndex;
            if (selItem == -1) {
                window.alert("You must first select an item on the left side.")
            } else {
                document.getElementById("ToChoose").add(document.getElementById("Userlist")[selItem], null);
            }
}
var user = document.getElementById("Userlist");
var seluser = user.selectedIndex;

if (seluser == -1) {
    window.alert("You must first select an item on the left side.")
}
else {
    var toChoose = document.getElementById("ToChoose");
    var newOption = user[seluser].cloneNode(true);
    toChoose.appendChild(newOption);
}

EDIT: I populate the Userlist from the database using the following code snippet:

string mycommand = "SELECT [id], [username] FROM [users]";
SqlDataAdapter x = new SqlDataAdapter(mycommand, ConnectionString);
DataSet ds = new DataSet();
x.Fill(ds, "users");
DataTable dt = ds.Tables[0];
Userlist.DataSource = dt;
Userlist.DataTextField = "username";
Userlist.DataValueField = "username";
Userlist.DataBind();

Answer №1

It seems like you may have used the incorrect Id for Userlist. Sharing all of your code in the view can make it easier for others to assist you.

Here's a sample to guide you, my friend :))

1) Generating sample data in the code-behind

public partial class About : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            DataTable dtName = new DataTable();

            //Adding Columns to the Table
            dtName.Columns.Add(new DataColumn("DisplayMember"));
            dtName.Columns.Add(new DataColumn("ValueMember"));

            //Populating with Values
            dtName.Rows.Add("Suits", "0");
            dtName.Rows.Add("Harvey Spector", "1");
            dtName.Rows.Add("Jessica Pearson", "2");
            dtName.Rows.Add("Mike Ross", "3");
            dtName.Rows.Add("Donna Paulson", "4");
            dtName.Rows.Add("Rachel", "5");

            //Binding data to Userlist     
            Userlist.DataSource = dtName;
            Userlist.DataTextField = dtName.Columns["DisplayMember"].ToString();
            Userlist.DataValueField = dtName.Columns["ValueMember"].ToString();
            Userlist.DataBind();
        }
    }

2) View

<%@ Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebFormSample.About" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: Title %>.</h2>
    <h3>Your application description page.</h3>
    <p>Use this area to provide additional information.</p>

    <select id="Userlist" name="cars" runat="server" multiple="true" style="width: 270px; height: 200px;">
    </select>

    <select id="ToChoose" name="cars" multiple="multiple" style="width: 270px; height: 200px;"></select>

    <input id="ButtonAddUsers" onclick="return validateUser();" type="button" value="Add" />


    <script>
        function validateUser() {
            var selItem = document.getElementById("MainContent_Userlist").selectedIndex;
            if (selItem == -1) {
                window.alert("You must first select an item on the left side.")
            } else {
                document.getElementById("ToChoose").add(document.getElementById("MainContent_Userlist")[selItem], null);
            }
        }
    </script>
</asp:Content>

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

Transmit HTML form information through a POST request to an ASP.NET web service

Having an HTML page with a contact form is great, but I'm facing the challenge of sending the data using AJAX. I attempted to send the data to a webservice without converting the structure to JSON format, but unfortunately, I did not succeed. Is ther ...

How to retrieve data from a nested object within a JSON array using JavaScript

When I use Logger.log(response.data.phone), the following data is displayed in my log: [{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}] My goal is to have the two ...

Having trouble modifying the fields in the formArray

https://i.sstatic.net/B4uTq.pngWorking with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backen ...

What is the timing for when the SignalR connection is terminated from the browser?

Currently, I am developing a chat application using SignalR 2.0, like many others in the same field. In my Win8.1 application, when the user closes the application, the hub receives the OnDisconnected event and removes the user from the list on the hub. A ...

As the value steadily grows, it continues to rise without interruption

Even though I thought it was a simple issue, I am still struggling to solve it. What I need is for the output value to increment continuously when I click the button. Here is the code snippet I have been working on: $('.submit').on('click&a ...

The textfields within the .map are not aligned next to each other

Adding the .map caused the name and quantity text fields to no longer display side by side. Before adding the .map, these two fields were in the same row but now they are not. <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}> ...

Clicking on an image in a jQuery autocomplete menu will trigger a data post to an Express

My jquery autocomplete menu is functioning properly, displaying a list of books with author, title, and book image. I am now looking to enhance it by allowing users to click on the book image and then have the book title posted to an express app.post metho ...

Emphasize a feature within a dynamic DIV

How can I highlight the span(class="tiny") element individually when its containing div is active or clicked? I have attempted to highlight the tiny span element without success, as only the entire div was highlighted. Here's the code snippet I' ...

How can you create a personalized sorting order using odata?

Within my AngularApp, I retrieve data from a WebAPI using OData queries. All the retrieved results contain both a date and an integer status code. The status codes range from 1 to 4. I am aiming to organize my results in such a way that all items with a ...

The element div is not permitted as a child of the element h5 in this particular scenario

My code snippet is as follows: $compile .= "<h5 data-count='".$acctemmpi. "' class='shortcode_accordion_item_title expanded_". $expanded_state . "'>" . $title . "<div class='ico'&g ...

Issue with React component timer becoming unsynchronized with numeric input field

My number field and countdown timer are not staying synchronized. Even though I can start and pause the countdown, whenever I try to change the number value after pausing, the numbers get out of sync. The gap between the two values keeps growing as time p ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Guide on incorporating database-sourced audio playback using buttons in PHP and HTML

Building my website with an audio player inside has been a bit challenging. I encountered an issue when trying to combine songs loaded from the database with a play button. My goal is to have the play button change when clicked and load the song from the d ...

React Alert: "Unable to modify while in the middle of a state transition"

Currently, I am working on developing an application that involves utilizing a toastr component. However, I am encountering an error when attempting to dispatch a redux action within this particular component. The error message displayed in the console is ...

Is it possible to disable other options when a checkbox is checked, but enable them all when unchecked using

I am trying to create a group of checkbox buttons where if one is checked, the others should be disabled. When the checked checkbox is unchecked, all checkboxes should be enabled. However, my current code is experiencing issues where all checkboxes become ...

Showing a series of text entries one after the other, each appearing with a smooth fade-in and fade-out

I am eager to showcase a list of text in a sequential order, implementing a fade-in/fade-out effect and concluding with the display of an image. Additionally, I aim to have all the text centered on the page. <div>a<div> <div>b</div> ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...