Robert
Robert

Reputation: 59

Get multiple selected values of Jquery's Select2 from code behind using asp.net

I'm combining Select2 with asp.net code behind to get the values. And now I want to get all the selected values using code behind too. But I can't get it to work. Here is my HTML code

<div class="form-group">
   <label>Multiple</label>
   <select class="form-control select2" id="ddLokasi" multiple="true" 
           runat="server" data-placeholder="Pilih Lokasi" style="width:100%;">
  </select>
</div>

As you can see, I manage to get the Select2 working on my web. Here's the screenshot : https://i.sstatic.net/vSccJ.jpg (sorry I can't embbed the image)

Now I want to get all the values that I already selected into an array. How to do this in code behind using asp.net VB ?

Thanks

Upvotes: 3

Views: 4441

Answers (2)

Bikee
Bikee

Reputation: 1197

Do something like this in your code-behind:

  For i As Integer = 0 To ddLokasi.Items.Count
            If (ddLokasi.Items(i).Selected)
                //Get values
                //ddLokasi.Items(i).Value
            End If
    Next

UPDATE

Dim listOfValues AS List(Of String) = new List(Of String)
        For Each item As ListItem In ddLokasi.Items
            If item.Selected Then
                listOfValues.Add(item.Value)
            End If
        Next

Upvotes: 3

MorKadosh
MorKadosh

Reputation: 6006

You can simply use jQuery's val() function to get the selected values see docs.

Select2 will serialize the selected options into an array, where the keys in the array are the selected values.

You are more than welcome to see a simpe example here: http://jsfiddle.net/42o2a37f/1/

When you have this array on the client side, you can use any way of data submitting to pass this array to the server side.

Upvotes: 0

Related Questions