Laziale
Laziale

Reputation: 8225

Determine if the checkbox is checked on click event in Knockout.js

I have this checkbox control:

<input type="checkbox" data-bind="attr: { id: 'prefix_12', attributeid: 12, poseId: $parent.Id }, click: $root.addEffect" />
                                            Add Option

And the event code:

self.addEffect = function (c, event) {
    var target = event.target;
}

What I want to know is how can I determine if the checkbox is checked or unchecked for each click event?

Upvotes: 0

Views: 2465

Answers (2)

Martin
Martin

Reputation: 400

The knockout way would be to bind checkbox against boolean property like this

<input type="checkbox" data-bind="checked: someBoolProperty" />

In viewmodel

self.someBoolProperty = ko.observable();

And rather than use click event, subscribe to the property

self.someBoolProperty.subscribe(function(newValue){
    if (newValue){
        // do whatever you want to do for checked checkbox
    } else {
        // unchecked
    }
}, self);

Upvotes: 1

shu
shu

Reputation: 1956

You can use event.currentTarget

if (event.currentTarget.checked) {
  // do the stuff
}
else {
 // do the stuff
}

Upvotes: 1

Related Questions