Mike Flynn
Mike Flynn

Reputation: 24325

Disable Radio Button With knockout.js

How do I disable a radio button with knockout.js? I don't want the user to be able to select it. My template below isn't working.

<div id="answers" data-bind="template: { name: 'answerTmpl', data: interactive.answers }">
    </div>

    <script id="answerTmpl" type="text/html">

        {{each(index, value) $data}}
        <div>
            <input type="radio" value="${index}" name="Answer" data-bind="disable: app.viewModel.avatars.speaking, checked: app.viewModel.interactive.answerSelected"/> <span>${value}</span> 
        </div>
        {{/each}}
    </script>

app.avatars.js

(function (app, $, undefined) {

    app.viewModel = app.viewModel || {};

    app.viewModel.avatars = {
        speaking: ko.observable(false),
        loaded: ko.observable(false)
    };

app.interactive.js

(function (app, $, undefined) {

    app.viewModel = app.viewModel || {};

    app.viewModel.interactive = {
        timeout: 1500,
        answers: ko.observableArray(),
        answerSelected: ko.observable(''),
        correctAnswer: ko.observable(-1),
        bookPage: ko.observable(1),
        chapterEmail: ko.observable(''),
        trialogue: {
            inProgress: ko.observable(false),
            response: ko.observable(''),
            conversation: ko.observableArray()
        }
    };

    app.interactive.init = function () {
         ko.applyBindings(app.viewModel);
    };

Upvotes: 2

Views: 4975

Answers (1)

Douglas
Douglas

Reputation: 37771

When you are using global variables instead of bound data, it looks like you need to explicitly evaluate the functions: http://jsfiddle.net/nFgnj/

<input type="radio" value="${index}" name="Answer" 
    data-bind="disable:app.viewModel.avatars.speaking(),
               checked:app.viewModel.interactive.answerSelected()" />

I don't really like this solution, because it relies on app being a global variable.

Upvotes: 3

Related Questions