Search code examples
jqueryhtmlbootstrap-select

Mark bootstrap-select options as selected on page load


I am using bootstrap-select to allow a user to select multiple options in a dropdown list. This jQuery code marks specific options as selected on page load. When the page loads, the list is auto-selected from code.

Example of the dropdown pre-populating

When I publish this page, I see that while the page source shows the correct jQuery code, the dropdown list is not pre-selecting. I see no errors on the console log. The page source below shows the correct "weeks" value from the View Model.

I cannot see any clear errors with the code, and it puzzles me that something can work on my local pc, but not on the published webpage. Is there anything else I can check, as no errors are being triggered?

This is what it looks like on the published page

// this comes from the View Model -- this is correct
var weeks = [];
weeks.push("Quarter 1 Week 1: Aug 7 - Aug 11");

// mark selected items in week list
var weekList = $("#Weeks > option");
$.each(weekList, function (a1, a2) {
    var $this = $(this);
    $.each(weeks,function(b1, b2) {
        if (a2.text === b2) {
            $this.attr("selected", "selected");
        }
    });
});

Solution

  • While the code is correct, the one last statement needed for it to apply was:

    $('.selectpicker').selectpicker('render');
    

    This forces the select list to refresh and apply the jQuery code above.