简体   繁体   中英

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?

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);

You can use event.currentTarget

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM