Disable select2 dropdown with knockout binding?

I have an MVC Razor project and in my opinion I have Html.TextBoxFor

with data-bind="disable: setRoot"

. This one is input

used by the Select2 jquery plugin. My problem is that the binding disable

is not working properly. This is my code:

<div class="control-label">Category</div>
                    <div class="input-group">
                        <div class="input-group-addon"><label><input data-bind="checked: setRoot" type="checkbox"> root</label>
                        </div>
                        @Html.TextBoxFor(m => m.Create.IdCategory, new { id = "QuickSearchMainCategory", data_bind = "disable: setRoot, value: model.Create.IdCategory", @class = "form-control" })
                    </div>

      

and my js:

self.setRoot = ko.observable(true);

            self.beRoot = ko.computed(function() {
                if (self.setRoot() === true) {
                    self.model.IdCategory(self.model.IdRootCategory());

                } else {
                    self.model.IdCategory(null);
                }
            });

$("#QuickSearchMainCategory").select2({
                placeholder: "Category search",
                minimumInputLength: 3,
                width: 'resolve',
                ajax: {
                    url: urlQuickSearchCategory,
                    contentType: 'application/json',
                    dataType: 'json',
                    type: 'POST',
                    traditional: true,
                    quietMillis: 400,
                    data: function(term, page) {
                        var data = {
                            term: term
                        };
                        return data;
                    },
                    results: function(data, page) {
                        return { results: data };
                    }
                },
                dropdownCssClass: "bigdrop",
                formatResult: function(item) { return item.id + " - " + item.label; },
                formatSelection: function(item) { return item.id + " - " + item.label; },
                escapeMarkup: function(m) { return m; }
            });

      

If I check the html the work is disabled, but not with all select2 elements, but only with the input with id QuickSearchMainCategory

. What should I do?

+3


source to share


1 answer


Select2 does not work with the 'disabled' binding because you have to explicitly tell select2 to disable itself using the built-in function.

You have to use this feature to disable / enable it:



$('#QuickSearchMainCategory').select2('disable');
$('#QuickSearchMainCategory').select2('enable');

      

You should do this in your ko viewmodel as it is not enough to set the HTML disabled attribute.

0


source







All Articles