I'm trying to build some HTML with Knockout that Jquery UI can turn into toggle buttons. What I need to arrive at is this:
<div id="status">
<input type="radio" id="status_ACTIVE" value="ACTIVE" name="status" /><label for="status_ACTIVE">Active</label>
<input type="radio" id="status_INACTIVE" value="INACTIVE" name="status" checked="checked" /><label for="status_INACTIVE">Inactive</label>
</div>
Using JQuery UI I can easily turn that into toggle buttons. But how do I generate that without using the now depreciated JQuery Templates? This is what I attempted to do:
Inside the javascript model:
self.statuses = [{Selected:true,Text:"Active",Value:"ACTIVE"},{Selected:false,Text:"Inactive",Value:"INACTIVE"}];
The markup:
<div id="status" data-bind="foreach: statuses">
<input type="radio" name="status" data-bind="value: Value, id: 'status_' + Value" /><label data-bind="text: Text, for: 'status_' + Value"></label>
</div>
This doesn't work. I don't think it likes how I'm trying to create that ID, or associate it with the for in the loop. It draws the buttons incorrectly, as two independent buttons and the click functionality doesn't work.
Even if I just specify the value as the id like: id: Value
and for: Value
it still doesn't work. Can I not set these attributes using knockout?
Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).
Adding this javascript solved my issue:
ko.bindingHandlers.id = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).attr('id', valueAccessor());
}
};
ko.bindingHandlers.forattr = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).attr('for', valueAccessor());
}
};
I did have to change for: 'status_' + Value
into foratt: 'status_' + Value
as for
is a reserved word.
Update: I could have also used the "attr" binding, like this:
attr: { for: 'status_' + Value }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With