jqueryhtmloffice-jsoffice-fabric

Jquery append in Office select input


I have a HTML Select with the office UI Fabric classes :

<div class="ms-Dropdown" tabindex="0">
   <label class="ms-Label">Modèles</label>
   <i class="ms-Dropdown-caretDown ms-Icon ms-Icon--ChevronDown"></i>
   <select id="modelsSelectbox" name="modelsSelectbox" class="ms-Dropdown-select">
        <option>Loading...</option>
   </select>
</div>

It's work well, but when i try to implement this Jquery code in the way to add new option it's doesn't work :

$('#modelsSelectbox')
   .append($("<option></option>")
   .attr("value",1)
   .text("d"));

If i delete the Office's classes, (A basic html select input) it's work ! So the problem come from the Office i think but i don't know why.

Somebody know ?


Solution

  • I am not an expert on Office fabric but as per my understanding, you can't simply use jQuery to modify fabric components. If you inspect the Elements, you can see Fabric generates additional DOM elements on the fly. I don't think there is a straightforward way to append dynamic options. One approach could be to reinitialise the Dropdown component:

    function initDropDown() {
       var $dropdown = $(".ms-Dropdown");
       $dropdown.find("select").innerHTML = "<option></option>";
       $dropdown.find(".ms-Dropdown-title").remove();
       $dropdown.find(".ms-Dropdown-items").remove();
       var $dropDownSelect = $(".ms-Dropdown-select");
       //your dynamic options
       $('<option value="0">option 1</option>').appendTo($dropDownSelect);
       $('<option value="1">option 2</option>').appendTo($dropDownSelect);
       $('<option value="2">option 3</option>').appendTo($dropDownSelect);
       //initialise component
       var DropdownHTMLElements = document.querySelectorAll('.ms-Dropdown');
       for (var i = 0; i < DropdownHTMLElements.length; ++i) {
           var Dropdown = new fabric['Dropdown'](DropdownHTMLElements[i]);
       }
    }
    

    If you don't want dynamic options, then simply initialise the component:

    function init() {
      var DropdownHTMLElements = document.querySelectorAll('.ms-Dropdown');
      for (var i = 0; i < DropdownHTMLElements.length; ++i) {
        var Dropdown = new fabric['Dropdown'](DropdownHTMLElements[i]);
      }
    }