Reputation: 5238
I am building a client that is connected to a socket.io
server. I have this code:
$(document).ready(function () {
Desktops.onData(function (desktops) {
var desktopsList = $("#desktops");
$.each(desktops, function (id, desktop) {
console.log(desktop.name);
desktopsList.append('<option value="' + id + '">' + desktop.name + '</option>');
});
});
Sockets.connect();
});
The callback inside Desktops.onData
gets called when the data comes back from the server. I then take this data(desktops)
and try to append it into a select element, which is used with a Bootstrap plugin. In the HTML side I have:
<select id="desktops" class="selectpicker" data-live-search="true">
</select>
I know that the problem is not in the data because console.log
works. I also know that the problem is not with my HTML or jQuery code because when I try to append to the select
outside of the callback, it works. So it must be something about doing jQuery inside callbacks. What can I do to make that jQuery work?
Thanks.
Upvotes: 1
Views: 294
Reputation: 337656
Given the plugin you've stated that you're using (Bootstrap Select), you need to call the refresh
method on it for it to recognise that new option
elements have been added to the underlying select
. Try this:
Desktops.onData(function (desktops) {
var desktopsList = $("#desktops");
$.each(desktops, function (id, desktop) {
console.log(desktop.name);
desktopsList.append('<option value="' + id + '">' + desktop.name + '</option>');
});
desktopsList.selectpicker('refresh'); // update the bootstrap select here
});
Upvotes: 2