简体   繁体   中英

Use of knockoutjs disable binding

I am trying to get an input box to be disabled when a checkbox is checked. I'm trying to use Knockoutjs to get this done, but it doesn't seem to work.

Here is my html:

<input id="input1" type="text" placeholder="Something Here" 
data-bind="disable: makeInvalid"/>
<input type="checkbox" id="chk1" data-bind="checked: makeInvalid"/>
<label>Make Textarea Invalid</label>

Here is my js:

var viewModel = {
        makeInvalid : ko.observable(false),        
};

ko.applyBindings(viewModel, document.getElementById("chk1"));

My fiddle is here:

https://jsfiddle.net/devEngine/3ag0881z/2/

I have attempted to follow knockout's instructions on the disable binding which they say is exactly the same as the enable binding, just in reverse:

http://knockoutjs.com/documentation/enable-binding.html

Can anyone tell me what I'm doing wrong?

Any help would be much appreciated.

This one is a super easy fix. Your apply bindings is only hitting the element with id chk1. The value of the observable will only be bound in that scope. Simply remove the second argument of your ko.applyBindings and it will work just fine.

 var viewModel = { makeInvalid : ko.observable(false), }; ko.applyBindings(viewModel); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <input id="input1" type="text" placeholder="Something Here" data-bind="disable: makeInvalid"/> <input type="checkbox" id="chk1" data-bind="checked: makeInvalid"/> <label>Make Textarea Invalid</label> 

You are missing knockout from your jsFiddle.

This is incorrect ko.applyBindings(viewModel, document.getElementById("chk1")); . You need to apply bindings to the input aswell as the checkbox. ko.applyBindings(viewModel);

See working jsFiddle: https://jsfiddle.net/3ag0881z/4/

<input type="checkbox" data-bind="attr: { disabled: isDisabled}, checked: isActive" />

.

var viewModel = {
        isDisabled: ko.observable(false),
        isActive : ko.observable(false)
};

ko.applyBindings(viewModel);

this is for enable/disable checkbox and also for checked/unchecked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM