I want to disable a button using knockout.js when the user clicks the button and the server is processing some data. I'm looking at the example in the knockout tutorials but appear to be missing something.
I have the enable:
part in the data-bind
:
<body>
<form id="form1" runat="server" >
<h1 style="text-align: center">Select the item(s) you want.</h1>
<br />
<br />
<div id="buttons" style="text-align: center">
<button data-inline="true" data-bind="click: submit, enable: canSubmit" >Submit</button>
<button data-inline="true" data-bind="click: cancel">Cancel</button>
</div>
I have set an observable in the view model to false. However, the button is enabled on the page when the view is initialized. So I think it is a data binding issue.
function ViewModel() {
var self = this;
self.selectedItems = ko.observableArray([]);
// we should start off not being able to click the submit button
self.canSubmit = ko.observable(false);
};
I want to have the button enabled until the user clicks the submit button, then disable it until the server has finished doing it's thing.
self.submit = function () {
// disable submit button
self.canSubmit = false;
// do stuff
self.canSubmit = true;
};
How do you bind the enable
observable value to the button?
You're mistakenly replacing your observable with straight js variables. canSubmit
is an observable, so change its value by calling the function:
self.submit = function () {
// disable submit button
self.canSubmit(false);
// do stuff
self.canSubmit(true);
};
The rest is fine as-is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With