Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Two ListBoxes dynamically populated w/JavaScript

Status
Not open for further replies.

EddieBR

Programmer
Joined
Jan 30, 2004
Messages
2
Location
US
I'm an asp.net newbie.
I have 2 listboxes (lbCouponList,lbCouponSelected).
The second listbox (lbCouponSelected) is populated using Javascript from the items selected in the first listbox (lbCouponList).
When the form is posted back, the lbCouponSelected listbox has none of the items inserted by the javascript client.
* I don't need to re-populate the listbox, I only need to read the items in the lbCouponSelected.*
I found out that if the listbox is pre-populated in the server, I'm able to read the listbox items pre-populated, but not the new items added by the client javascript code.
Any idea how can I read the dynamically populated listbox ?

thanks
 
Eddie,
The changes you make to a list box through client javascript live on the client and the server doesn't see them. Before you post the form back to the server, you need to save the added items into a control that both client and server code can see. A very good candidate for this is the HtmlInputHidden control.

What you would do is write a javascript function that saves the added items into the value property of the HtmlInputHidden control. This function would run right before the postback. Now, on the server, you would read the value property of the HtmlInputHidden control and get the added items.

The javascript function I use looks like this:
Code:
// This function runs just before the postback
function SaveAddedItems(hiddenControl)
{
   for (i = 0; i < lst.length; i++)
   {
      added += &quot;;&quot; + lst.options[ i ].value;
   }
   hiddenControl.value = added;
}

Then, on the server I have a function that works with the selected items. It looks like this:
Code:
// C# code on the server parses added items.
private void WorkWithAddedItems()
{
   string added = hiddenControl.value;
   string addedArr[] = added.Split(';');
   // ...
   // Do whatever I want with the items.
}

Notice this: On the javascript function, I use a semicolon, &quot;;&quot;, to separated each added item but you could use whatever is suitable to you. Also, I use the value property of the list item, as opposed to its text property, but again, you should do whatever is suitable to you.

JC

We don't see things how they are; we see them how we are.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top