Arbiter
Arbiter

Reputation: 1024

Generating IDs within Knockout Foreach loops

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?

Upvotes: 8

Views: 8262

Answers (1)

Arbiter
Arbiter

Reputation: 1024

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 }

Upvotes: 10

Related Questions