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();