Search code examples
knockout.jsknockout-mapping-pluginknockout-validationknockout-mvc

How can I dynamically disable a text box using Knockout's observables?


I'm implementing register form and when I click on submit button, I want to disable textbox using Knockout.

I have tried the following:

var viewModel = {
    Textboxcontrol: ko.observable(true), // by default textbox is enable to edit
    Register: {
        Init: function () {
        Textboxcontrol= false; // Updating the value to false 
                               // so Textbox should be disabled.
    }
};

ko.applyBindings(viewModel);

On UI I wrote as follows

<input  data-bind="value: Name, enable: Textboxcontrol" 
        type="text" autocomplete="off" />

But the problem is if I change the value to Textboxcontrol= false; also its taking the value as True only.. and textboxes are not disabling.


Solution

  • Since Textboxcontrol is an observable, you must change its value by calling it as a function. Plus, you must use this to access the Textboxcontrol property inside your "Init" function :

    var viewModel = {
      Name: ko.observable(''),
      Textboxcontrol: ko.observable(true),
      Register: {
        Init: function () {
          this.Textboxcontrol(false);
        }
      }
    };
    ko.applyBindings(viewModel);