Selected dropdown does not work for dynamically populated options

I use the Favorites drop-down list and dynamically populate this option. search in the dropdown does not work, even I can not enter text, but it works fine when the dropdowns are static. Please, help.

<select id="test" class="chosen-select"> 
    <option>Select1</option> 
</select> 

var div2=[]; 
div2.push("<option value='1'>ALL1</option>"); 
div2.push("<option value='2'>ALL2</option>"); 
div2.push("<option value='3'>ALL3</option>"); 
div2.push("<option value='4'>ALL4</option>"); 
div2.push("<option value='5'>ALL5</option>"); 
$("#test").html(div2.join('')); 

$("#test").trigger("chosen:updated");
+4
source share
1 answer

Be sure to call .chosen()after dynamically populating the drop-down list.

Here is the fiddle https://jsfiddle.net/npzs2bt7/

EDIT 1:

You probably didn't call chosen()in the drop-down list before you could call trigger("chosen:updated").

https://jsfiddle.net/npzs2bt7/1/

2:

Jquery 1.9.0, Chosen.Jquery 1.1.0

html (chosentest.html) .

<html>
    <head>
        <title>chosen demo</title>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
        <style type="text/css">
            #test
            {
              width:100px;
            }
        </style>
    </head>
    <body>
        <select id="test" class="chosen-select"> 
          <option>Select1</option> 
        </select>
        <button class="btn">Click to see selected value</button>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                //first call chosen()
                $("#test").chosen();

                 var div2=[]; 
                 div2.push("<option value='1'>ALL1</option>"); 
                 div2.push("<option value='2'>ALL2</option>"); 
                 div2.push("<option value='3'>ALL3</option>"); 
                 div2.push("<option value='4'>ALL4</option>"); 
                 div2.push("<option value='5'>ALL5</option>"); 
                 $("#test").html(div2.join('')); 

                 //this will bind the updates
                 $("#test").trigger("chosen:updated"); 

                 //text button to alert selected value from dropdown
                 $(".btn").click(function(){
                    alert($("#test").val());
                }); 
            });
        </script>
    </body>
</html>
+4

All Articles