Below, there are two snippets. In the first one, I'm using a traditional select menu and I'm loading select menu options from JSON data. The first snippet is fine and works as expected. The JSON data loads, etc.
On the second snippet, I'm using the same fetch-api method, but I've included the chosen-select class with the select menu.
When using jQuery Chosen on a select menu, why doesn't the data load?
w/ JSON Data
let users = document.getElementById("placeholder");
let newDefault1 = new Option("Select a User", null, false, true);
newDefault1.disabled = true;
users.add(newDefault1);
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => {
data.forEach((user) => {
let option = new Option(user.name, user.id);
//console.log(option);
users.add(option);
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
<div class="panel-body">
<div class="col-md-6 b-r">
<div class="form-group">
<label for="form1">Select User</label>
<select class="form-control" name="placeholder" id="placeholder"></select>
</div>
</div>
</div>
</div>
w/ JSON Data using chosen-select I have added code to notify chosen that the select has been modified, but it's still no loading the data.
//required to instantiate jQuery Chosen
$(".chosen-select").chosen({
width: "100%"
});
let users = document.getElementById("placeholder");
let newDefault1 = new Option("Select a User", null, false, true);
newDefault1.disabled = true;
users.add(newDefault1);
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => {
data.forEach((user) => {
let option = new Option(user.name, user.id);
//console.log(option);
users.add(option);
});
});
$('#placeholder')
.find('option:first-child').prop('selected', true)
.end().trigger('chosen:updated');
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap-chosen@1.4.2/bootstrap-chosen.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<div class="container">
<div class="panel-body">
<div class="col-md-6 b-r">
<div class="form-group">
<label for="form1">Select User</label>
<select class="form-control chosen-select" name="placeholder" id="placeholder"></select>
</div>
</div>
</div>
</div>