UserEsp
UserEsp

Reputation: 426

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

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.

Upvotes: 0

Views: 166

Answers (1)

caseyWebb
caseyWebb

Reputation: 2086

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"

Upvotes: 0

Related Questions