Move items from one listbox to other using javascript

Some Javascript code snippet that i wanted to Share..

To move items from one listbox to the other - I am using three methods here.

One for adding the selected Products from listbox1 to listbox2 and then calling a AddProdInHiddenField method for adding listbox2's selected items in a hidden field.

Second method will remove the selected items from listbox2 and will add them back in listbox1 and again I call the AddProdInHiddenField method to save newly values for the listbox2 in a hidden field.

Third method is just for saving listbox2's values in a hidden field. This way you will always have updated selected items in your hidden fields.

//Works on ">>" button between the listboxes

function AddProducts()
{

var Source = document.getElementById('<%=lbxProducts1.ClientID%>');

var Target = document.getElementById('<%=lbxProducts2.ClientID%>');

if ((Source != null) && (Target != null))
{
while ( Source.options.selectedIndex >= 0 )
{
var newOption = new Option(); // Create a new instance of ListItem
newOption.text = Source.options[Source.options.selectedIndex].text;
newOption.value = Source.options[Source.options.selectedIndex].value;

//Append the item in Target
Target.options[Target.length] = newOption;

//Remove item from listbox1
Source.remove(Source.options.selectedIndex);

}
// Adding the listbox2 values in hidden field
AddProdInHiddenField();
return false;
}
}


function RemoveProducts()
{
var Source = document.getElementById('<%=lbxProducts1.ClientID%>');

var Target = document.getElementById('<%=lbxProducts2.ClientID%>');

if (Target != null)
{
while (Target.options.selectedIndex >= 0 )
{
// Create a new instance of ListItem
var newOption = new Option();
newOption.text = Target.options[Target.options.selectedIndex].text;

newOption.value= Target.options[Target.options.selectedIndex].value;

Target.remove(Target.options.selectedIndex);
Source.options[Source.length] = newOption;
}

AddProdInHiddenField();
}
return false;
}

function AddProdInHiddenField()
{
var list = document.getElementById('<%=lbxProducts2.ClientID%>');

var hdnField = document.getElementById('hdnField');
hdnField.value = "";
for(var i = 0; i < list.options.length; ++i)
{

hdnField.value += list.options[i].value + ",";
}
}

0 comments:

Post a Comment

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com