I try to add checkboxes to my page by using Knockout.
But those dynamically added checkboxes can't be checked by clicking on them.
If I add a box using jQuery, the generated HTML differs from a Knockout checkbox. The input gets wrapped in another <div class="ui-checkbox">.
Also there is no difference if the custom binding checkbox is not used.
Has someone an idea how to solve this problem?
- jQuery: 1.10.2
- jQuery-Mobile: 1.3.2
- Knockout: 2.3.0
Here is a fiddle: http://jsfiddle.net/USpX5/
HTML:
<div id="fiddle" data-bind="foreach: boxes">
<label>
<input type="checkbox" />
<span data-bind="text: name"></span>
</label>
</div>
JS:
var BoxModel = function(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
};
var MainModel = function()
{
this.boxes = ko.observableArray([]);
}
var main = new MainModel();
$('#add-ko').click(function() {
var i = $('#fiddle').find('input[type=checkbox]').length + 1;
main.boxes.push(new BoxModel('id'+i, 'name'+i));
});
$('#add-jqm').click(function() {
var i = $('#fiddle').find('input[type=checkbox]').length + 1;
$('#fiddle').append('<label><input type="checkbox" /><span>name'+i+'</span></label>').trigger('create');
});
// http://stackoverflow.com/a/15841271/2710739
ko.bindingHandlers.checkbox = {
init: function(element, valueAccessor) {
// set the dom element to a checkbox and initialize it (for jquerymobile)
var checkbox = $(element);
checkbox.checkboxradio();
checkbox.attr('type', 'checkbox');
},
update: function(element, valueAccessor) {
// update the checked binding, i.e., check or uncheck the checkbox
ko.bindingHandlers.checked.update(element, valueAccessor);
// and refresh the element (for jquerymobile)
var checkbox = $(element);
checkbox.checkboxradio('refresh');
}
};
ko.applyBindings(main);
Resulting HTML (copied from Chrome DevTools):
<div id="fiddle" data-bind="foreach: boxes">
<!-- added with ko -->
<div class="ui-checkbox">
<label data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-theme="c" data-mini="false" class="ui-checkbox-off ui-btn ui-btn-corner-all ui-fullsize ui-btn-icon-left ui-btn-up-c">
<span class="ui-btn-inner">
<span class="ui-btn-text">
<span data-bind="text: name">name1</span>
</span>
<span class="ui-icon ui-icon-checkbox-off ui-icon-shadow"> </span>
</span>
</label>
<div class="ui-checkbox"><!-- additional ui-checkbox class maybe causes the problem -->
<input type="checkbox" data-bind="checkbox:true">
</div>
</div>
<!-- added with jqm -->
<div class="ui-checkbox">
<label data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-theme="c" data-mini="false" class="ui-checkbox-off ui-btn ui-btn-corner-all ui-fullsize ui-btn-icon-left ui-btn-up-c">
<span class="ui-btn-inner">
<span class="ui-btn-text">
<span>name2</span>
</span>
<span class="ui-icon ui-icon-checkbox-off ui-icon-shadow"> </span>
</span>
</label>
<input type="checkbox">
</div>
</div>