Jonathan Kittell
Jonathan Kittell

Reputation: 7503

How to enable or disable a button using knockout.js

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?

Upvotes: 14

Views: 20109

Answers (2)

Will Jenkins
Will Jenkins

Reputation: 9907

You're not updating your observable value, you're changing the reference of self.canSubmit so it points to a boolean.

change your self.submit function to:

self.submit = function () {
        // disable submit button
        self.canSubmit(false);
        // do stuff
        self.canSubmit(true);
};

Upvotes: 5

Jamiec
Jamiec

Reputation: 136174

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.

Upvotes: 8

Related Questions