1

this is my code:

HTML:

<div>
   <input type="button" id="btnEnable" value="Enable" />
   <input type="button" id="btnDisable" value="Disable" />
</div>
<div id="myDiv">Some Text</div>
<textarea rows="5" id="someText" data-bind="enable: enableText"></textarea>

css:

.enabled{
  background-color: green;
}
.disabled{
  background-color: red;
}

javascript:

$(document).ready(function () {
  $("#myDiv").addClass("enabled").html(" Enabled");

  $("#btnEnable").click(function () {
    $("#myDiv").removeClass("disabled");
    $("#myDiv").addClass("enabled").html(" Enabled");
  });
  $("#btnDisable").click(function () {
    $("#myDiv").addClass("disabled").html(" Disabled");
    $("#myDiv").removeClass("enabled");
  });
  var viewModel = function(){
    enableText =  ko.observable(true)
  }
  ko.applyBindings(viewModel);
});

when i click on the disable button, the enabled css class is removed. At this point, i need to disable the textarea by KO observable viewModel.

var viewModel = function(){
    enableText =  ko.observable(here must return false when the enable css class is removed)
}

1 Answer 1

2

You need the click, css and text bindings :

$(document).ready(
    var viewModel= function () {
        var self = this;
        self.enableClick = function () {
            self.enable(true);
        };
        self.disableClick = function () {
            self.enable(false);
        };
        // Stores the enable state
        self.enable = ko.observable();
        // Get a text representation of the state 
        self.enableText = ko.computed(function(){
           return self.enable() ? 'Enabled' : 'Disabled';
        });
    };
    ko.applyBindings(new viewModel());
});

The view :

<div>
   <input type="button" data-bind="click: enableClick" value="Enable" />
   <input type="button" data-bind="click: disableClick" value="Disable" />
</div>

<div data-bind="text: enableText, css :{'enabled' : enable,'disabled' : enable() != true }">Some Text</div>
<textarea rows="5" id="someText" data-bind="enable: enable"></textarea>

See fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

@pasluc74669,"something else" could you be more specific ?
it works fine, but i need something else: i need to enable/disable the textarea, by the knockout modelview, when a css class is removed/added.Is it possible?
Yes it's possible. In 99% cases it's bad idea, because KO is responsible of changing the UI. I mean you change the viewmodel and KO alter the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.