Change value attribute of checkbox base on checked value with knockout JS

156 Views Asked by At

I'm trying to a checkbox and send the value YES or NO in my submitted form, base in if is checked or no but the value is not updated here is my code:

self.checkbox = ko.observable("No");
    self.is_checked = ko.computed({
        read: function (data) {
            return false;
        },
        write: function (data, event) {  self.is_checked() ? self.checkbox('Yes'):  self.checkbox('No');}

    });

data-bind="checked: is_checked, checkedValue:checkbox"

any clues or links to read, please.

1

There are 1 best solutions below

0
caseyWebb On

Your computed read function should return true or false so the UI is updated by the checked binding, and you can remove checkedValue entirely (checkedValue usually only makes sense to use with radio elements).

self.checkbox = ko.observable("No");
self.is_checked = ko.pureComputed({
  read: () => self.checkbox() === "Yes",
  write: (v) => self.checkbox(v ? "Yes" : "No")
})
data-bind="checked: is_checked"