I am using bootstrap toggle here is the html code
<input data-bind="checked: Active" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="primary" data-offstyle="danger" type="checkbox">
<button type="button" class="btn btn-primary" data-bind="click: AddEditSubCategory">Save</button>
The checked binding is not working. here is the knockout.js code
var SubCategoryViewModel = {
Active: ko.observable(),
AddEditSubCategory: function () {
console.log(SubCategoryViewModel.Active());
}
I am getting an undefined value in console
$(document).ready(function () {
ko.applyBindings(SubCategoryViewModel, document.getElementById("categoryMain"));}
Can anyone tell me how to solve this issue.
The design of checkbox is like below image and I, am using this library http://www.bootstraptoggle.com/ . If I, don't use data-toggle="toggle" the binding is working perfectly.
as mentioned by Jason Spake you will need a custom binding. here is a working fiddle. http://jsfiddle.net/MBLP9/358/
here is the binding
ko.bindingHandlers.bootstrapToggleOn = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$elem = $(element);
$(element).bootstrapToggle({
on: 'Yes',
off: 'No',
onstyle: 'primary',
offstyle: 'danger'
});
if (ko.utils.unwrapObservable(valueAccessor())){
$elem.bootstrapToggle('on')
}else{
$elem.bootstrapToggle('off')
}
$elem.change(function() {
if ($(this).prop('checked')){
valueAccessor()(true);
}else{
valueAccessor()(false);
}
})
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var vStatus = $(element).prop('checked');
var vmStatus = ko.utils.unwrapObservable(valueAccessor());
if (vStatus != vmStatus) {
$(element).bootstrapToggle('toggle')
}
}
};