Wednesday, October 22, 2014

Jquery-Chosen-Knockout in a Dialog or Window Not Working?

If you are loading a Chosen element in a pop-up dialog box or window, you may find that the "multiple" types or "multiselect" type of element does NOT display the selectedOptions that you specified on the data-bind. You need to trigger an update by passing a reference of window to the open function.
This was the template that was loaded into the dialog window (located in a .cshtml file):
  1. <script type="text/html" id="junk-template">
  2. <div>
  3. <!--set tabindex of dropdown to prevent from auto opening when editing-->
  4. <select id="myItems" tabindex="-1" data-placeholder=" " data-bind="chosen: MyOptions, optionsText: 'Text', optionsValue: 'Value', selectedOptions: MySelectedOptions" multiple="multiple"></select>
  5. </div>
  6. </script>
This is the code in the Javascript file to load, data-bind and open the window. NOTICE 2 things, you must use the z-index and pass the window by reference to the open function. In order to resolve issues with chosen in a popup window the z-index must be set.
  1. function _openMyWindow(myOptions) {
  2. var selectedOptions = _getOptions();
  3. $window = $("<div/>");
  4. $window.append($('#junk-template').html());
  5. if (!myVM) {
  6. myVM = {
  7. MyOptions: ko.observableArray(myOptions),
  8. MySelectedOptions: ko.observableArray(selectedOptions != undefined ? selectedOptions : [])
  9. }
  10. }
  11. ko.applyBindings(myVM, $window[0]);
  12. $window.Window({
  13. width: '450px', height: 'auto', modal: true, zIndex: 998, maximizable: false, open: _openWindow($window), title: "Junk Title"
  14. });
  15. }
Now, pay attention here, see I am using the window reference to trigger the chosen element update!
  1. function _openWindow(container) {
  2. var element = $(container).find('#myItems');
  3. if (element != null) {
  4. element.trigger("chosen:updated");
  5. }
  6. }
Hope you could follow that and I hope it helps!

No comments:

Post a Comment