Turn on / off input - knockout

I want to make my form editable after clicking a button.

I am writing code to click a button, but I cannot change the state of the inputs on the form.

viewModel.test= function () {
   //code here
}
<input type="text"/> // Enable/Disable this

Is it possible to disable / enable all inputs in the form or do I just need to do this one by one?

+4
source share
2 answers

With a clean knockout, you can do this by basically switching the observable isDisabled, which updates the attribute of the disabledrelated item. You can use knockout binding attrto set attributes on elements.

var ViewModel = function() {
    var self = this;
    self.isDisabled = ko.observable(false);
    this.disable = function(){
        self.isDisabled(true);
    }
    this.enable = function(){
         self.isDisabled(false);
    }
};

ko.applyBindings(new ViewModel()); 


<div>
    <input type="text" data-bind="attr : {'disabled' : isDisabled}"/> // Sets disabled attribute if isDisabled is true.
    <input type="text" data-bind="attr : {'disabled' : isDisabled}"/>
    <button data-bind="click : disable">Disable</button>
    <button data-bind="click : enable">Enable</button>
</div>

https://jsfiddle.net/xggu9Lv2/2/

+9
source

, IE8 , / :

function vm() {
  var self = this;
  self.hasForm = ko.observable(false);
  self.cellphoneNumber = "";
  self.personName = ""
}

ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <input type='checkbox' data-bind="checked: hasForm" />I have a cellphone & a name
</p>
<p>
  <form id="form">
    <label>Your cellphone number:</label>
    <input type='text' data-bind="value: cellphoneNumber, enable: hasForm" />
    <label>Your Name:</label>
    <input type='text' data-bind="value: personName, enable: hasForm" />
  </form>

</p>
Hide result

... ko .

+3

All Articles