Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable or disable a button using knockout.js

Tags:

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?

like image 966
Jonathan Kittell Avatar asked Mar 05 '15 14:03

Jonathan Kittell


1 Answers

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.

like image 93
Jamiec Avatar answered Sep 18 '22 19:09

Jamiec