简体   繁体   中英

set selected value in jquery multiselect dropdown

I have a scenario that I have to set the multiple values as selected in the multi-select dropdown as shown in below screenshot.

Following is my model and I have ExcursionList as the type of string List there.

 public class HotelInfo
{
 public List<string> ExcursionList { get; set; }
}

I am returning my hotel information as a JSON result in the controller and retrieve that value in jquery as shown in below code.

function LoadHotelDetails(data) {
    if (data) {
        $.each(data.ResultList, function (index, value) {
            $("#hotelName").val(value.HotelName);
            $("#nights").val(value.Nights);

            // this console.log print ["* EARLY CHECK-IN", " * LATE CHECK-OUT", " *- REFUND -*"] value to console.
            console.log(value.ExcursionList);

            $("#excursion").val(value.ExcursionList);

            $('#excursion').multiselect('refresh');

}

As in console.log value, I am getting 3 selected value. But in my dropdown, It's selecting only one value as shown in the below screenshot.

I am really thankful if anybody can help me here.

Note: val is use set value using value attribute of drop-down eg

<select>
 <option value="1" > option 1  </option>
 <option value="2" > option 2  </option>
 </select>

In your case you need to set value using text().

$("#excursion").text(value.ExcursionList).multiselect('refresh');

Try this

var tempArr = [];

 function LoadHotelDetails(data) {
if (data) {
    $.each(data.ResultList, function (index, value) {
        $("#hotelName").val(value.HotelName);
        $("#nights").val(value.Nights);

        // this console.log print ["* EARLY CHECK-IN", " * LATE CHECK-OUT", " *- REFUND -*"] value to console.
        console.log(value.ExcursionList);
        tempArr.push(value.ExcursionList)
    }); //closing of each

        $("#excursion").text(tempArr).multiselect('refresh');
      //  $('#excursion').multiselect('refresh');
  tempArr = []; //empty temp array
    }

Thanks For the help. I was able to fix the issue using razor view engine and C#. Without using jquery.

 @Html.ListBoxFor(model => model.ExcursionList, ((IEnumerable<SelectListItem>)ViewBag.ExList), new { @class = "form-control", id = "excursion", multiple = "multiple" })

The above works perfectly by selecting the dropdown values correctly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM