I want a way to have a simple y/n radio button input that gives me a boolean I can play with. I've got it working like this, using a writeable observable and the checked binding:

js:

var viewModel = {    
...
    salary_ind_yn: ko.pureComputed({

        read: function () {            
        },
        write: function (value) {
            if (value == "yes") {
                viewModel.salary_ind(true);
            } else if (value =="no") {
                viewModel.salary_ind(false);
            }
        }
    }),
    salary_ind: ko.observable(),
...
}

html:

<div class="form-field">
<label>Use salary indicator?</label>
<span for="salary_ind_yes"><input type="radio" name="salary_ind" value="yes" data-bind="checked:salary_ind_yn" />&nbsp;Yes</span>&nbsp;&nbsp;
<span for="salary_ind_no"><input type="radio" name="salary_ind" value="no" data-bind="checked:salary_ind_yn">&nbsp;No</span>
</div>

But with this syntax I can't figure out how to get validation to work... for other fields have got it working with the .extend bit like this:

email_input: ko.observable().extend({
        required: true,
        email:true,
}),

So thought if I set it so the default is that the 'no' button is checked, that would mean I wouldn't need to check if user has clicked one or the other, but can't figure out how to do that either using the pureComputed / read / write syntax.

Any help greatly appreciated! Cheers!

1

There are 1 answers

1
user3297291 On BEST ANSWER

You should be able to use a regular observable with the checkedValue data-bind:

var vm = {
  yn: ko.observable(true)
};

vm.yn.subscribe(console.log.bind(console, "New checked value:"));

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<label><input type="radio" name="yn" data-bind="checked: yn, checkedValue: true">yes</label>
<label><input type="radio" name="yn" data-bind="checked: yn, checkedValue: false">no</label>