user123456789
user123456789

Reputation: 2004

How to show multiple selected items in an ListBox

I have a ListBox where you can select multiple items and these save to a database. That all works fine but when I go back into the ListBox to view the items only the first one is selected, even though I had selected 3.

ListBox:

<asp:ListBox runat="server" SelectionMode="Multiple" ID="txtEdtContactDocuments"></asp:ListBox>

Code:

for (var i = 0; i < document.getElementById('<%= txtEdtContactDocuments.ClientID %>').length; i++) {
  for (var x=0;x<result.Docs.length;x++) {
        if (Number(document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].value) == Number(result.Docs[x].DocType)) {
              document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].selected = "selected";
              } else {
                 document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].selected = "";
                 document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].selected = false;
              }
        }
  }

The loops are looking correctly, it does find the 3 items I selected but they are not getting highlighted in the list:

enter image description here

I also tried document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].selected = true; but that change anything. Only the first item still got selected.

Upvotes: 0

Views: 451

Answers (2)

rocky
rocky

Reputation: 7696

It's an algorithmical issue. Assuming that there are more than one items in the result.Docs collection, you are overwriting what you might have set in earlier iterations of the for (var x=0;x<result.Docs.length;x++) loop.

Your algorithm should work if you put break; statement after this line: document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].selected = "selected";. It will terminate the inner loop when the appropriate item is found.

However, I'd recommend refactoring the code and getting rid of the inner loop completely. You can replace it with a LINQ query, for instance.

Note: there's no need to use jQuery or any other JS framework. You can easily do achieve the task with vanilla JavaScript: https://jsfiddle.net/hjybjz3e/

Upvotes: 2

Drummad
Drummad

Reputation: 722

Try using jQuery to set the selected options.

Replace

document.getElementById('<%= txtEdtContactDocuments.ClientID %>')[i].selected = "selected";

With:

$('#<%= txtEdtContactDocuments.ClientID %>').eq(i).attr("selected", "true");

.eq() is a jQuery function to select the object at a specific index much the same us using [] notation.

Upvotes: -1

Related Questions