Rod Rod - 2 months ago 7
jQuery Question

why isn't my dynamic button disabled with knockoutjs?

I'm not sure why my dynamic button not disabled using knockoutjs?

Original working dynamic html and knockoutjs: Link1

Work in progress: Link2

var viewModel = {
first: ko.observable("Bob"),
last: ko.observable("Smith"),
isEnabled: ko.observable("disabled")
};

viewModel.fullName = ko.dependentObservable(function() {
return this.first() + " " + this.last();
}, viewModel);

function addDynamicContent() {
$("#main").append("<div id='dynamic' data-bind='text: fullName'></div><input id='Button1' type='button' value='Hello World' data-bind='disabled=isEnabled' />");

ko.applyBindings(viewModel, $("#dynamic")[0]);
}

ko.applyBindings(viewModel);


enter image description here

Answer

Your data bind syntax for the disable binding is incorrect in your appended HTML, and your reapplication of bindings isn't quite correct.

Change your enabled/disabled observable to use a boolean value

isEnabled: ko.observable("disabled")

should be:

isEnabled: ko.observable(true)

Correct the disable data bind syntax in your appended markup

$("#main").append("<div id='dynamic' data-bind='text: fullName'></div><input id='Button1' type='button' value='Hello World' data-bind='disabled=isEnabled' />");

should be:

$("#main").append("<div id='dynamic' data-bind='text: fullName'></div><input id='Button1' type='button' value='Hello World' data-bind='disable: isEnabled' />");

Change your binding update to re-bind the whole viewmodel

ko.applyBindings(viewModel, $("#dynamic")[0]);

should be:

ko.cleanNode($("#main")[0]);
ko.applyBindings(viewModel);

Updated JSFiddle.

This will get your example functional, however if you are working with dynamic content, I strongly recommend using some additional bindings instead of appending HTML and redoing your bindings every time. Have a look at Observable arrays, the template binding, and working with collections.

I threw together another JS Fiddle example that shows another approach to dynamic content and bindings using the bindings mentioned above.

Comments