knockout.js and listen to check event on checkbox

Mike Flynn picture Mike Flynn · May 24, 2012 · Viewed 65.3k times · Source

I'm trying to get a function to execute when a checkbox is checked or unchecked to verify all checkboxes are unchecked but it never gets executed. I assume I'm not doing it correctly.

@Html.CheckBox("Subscription", new{ data_bind="disable: Disabled, checked: Checked, click: $parent.allSubscriptionsUnchecked"} ) 

Answer

RP Niemeyer picture RP Niemeyer · May 24, 2012

You can add both a checked and click binding to an input. However, you would want to return true; from the click handler. This will allow the default action to proceed (the checkbox will be checked/unchecked).

Here is a sample: http://jsfiddle.net/rniemeyer/cnkVA/

An alternative technique is to push this logic into your view model and subscribe to changes to a boolean observable and execute your action like: http://jsfiddle.net/rniemeyer/cnkVA/2/