Search code examples
jqueryasp.net-mvcrazordropdownjquery-chosen

chosen-select dropdown not working by jquery MVC


I'm using dropdown with multiple select with groups in my mvc razor page. I'm following below link and using Multiple Select with Groups dropdown.

Harvest Multiselect Dropdown Link

It is working fine if I implement in razor view like below sample:

....
<select data-placeholder="Search option" id="Mainlist[0].SubList" class="chosen-select" multiple tabindex="6" name="MainList[0].SubList">
     <option value=""></option>
     @foreach (var mainListItem in Model.MainList)
     {
          <optgroup label="@mainListItem.Name">
           @foreach (var subListItem in mainListItem.SubList)
           {
               <option id="report">@subListItem.Name</option>
           }
           </optgroup>
      }
</select>
....

Above razor code for chosen dropdown working fine like in below image: razor chosen-select dropdown

But I have a requirement to add more multi select dropdowns on button click event of jquery. I tried below code in jquery:

var newRow =
"<select data-placeholder='Search option' id='Mainlist[1].SubList' class='chosen-select' multiple tabindex='6' name='MainList[1].SubList'>" +
        "<option value=''></option>" +
        "<optgroup label='Main List Item 1'>" +
        "<option id='report'>Sub List Item 1.1</option>" +
        "<option id='report'>Sub List Item 1.2</option>" +
        "</optgroup>" +
        "<optgroup label='Main List Item 2'>" +
        "<option id='report'>Sub List Item 2.1</option>" +
        "<option id='report'>Sub List Item 2.2</option>" +
        "</optgroup>" +
        "</select>";

$('#TestTable tr:last').after(newRow);

First problem is : I can't implement foreach loop in newRow variable. Second one is : If I try to manage whole list manually like above code, then also List is not coming properly like below image: jquery chosen-select dropdown

Any idea what is causing it? and how can I make dropdown working by jquery? or is there any other way to add same dropdown by jquery?

I already tried $(".chosen-select").chosen() from below link:

chosen-select link


Solution

  • Check you are initializing the chosen after the select is added to dom. Could you tell me the error you are facing.