Search code examples
postknockout.jshtml-selectdisabled-input

How to enable/disable select tag and post it (even if disabled) with knockout


I have a complex form with many selects whose state (enabled/disabled) depends on the value of some other controls, so it could happen that these selects are disabled when submitting the form (and the select value is not posted). I need to post the selected value even in the case the user is not allowed to change the select.

I saw some solutions here HTML form readonly SELECT tag/input (mainly the solution is to have an hidden field synchronized with the disabled select).

I am thinking to taking a slightly different approach: I want to use knockout (already used in the project) to display the select only when the data is editable, and display a readonly input (or a div/span) otherwise.

How can I use knockout to simplify this approach?


Solution

  • In my viewModel I define the property relative to the state of the select, the property bounded to the select value and a computed observable that "reads" the description of the selected option in the select:

    AppViewModel: function () {
            var self = this;
            self.SelectVisible = ko.computed(function () {
                return true;  // return true or false depending on your context
            }, self);
            self.Category = ko.observable("");
            self.CategoryText = ko.computed(function () {
                return $("#Category option[value='" + self.Category() + "']").text();
            }, self);
            // other code ...
    }
    

    In the page I have a select always enabled and a readonly input whose visibility is mutually esclusive and depends on a viewModel property:

    <select name="Category" id="Category" data-bind="value: Category, visible: SelectVisible">
       <option value="S">Standard</option>
       <option value="N">CatN</option>
       <option value="C">CatC</option>
    </select>
    <input style="display: none;" type="text" readonly="readonly" data-bind="value: CategoryText, visible: !SelectVisible()"/>