CleverPatrick
CleverPatrick

Reputation: 9483

Pattern for Uniquely Identifying ForEach bound elements in KnockoutJS

I have a knockoutjs viewmodel that contains a list of contact types for a person (phone number, email, physical address, etc...).

Each different contact type has a different Template that it binds to. (so a phone number field looks different from physical address field, for instance).

This works fine.

Now I need to be able to give each of the elements in a template a unique ID so I can reference them in markup and javascript. For instance, each contact type has a field in it called AddressType where the user can put in things like Home Address, Work Email, etc... It is the same field for each contact type. The html markup looks like this:

<label for='AddressType'>
    Type 
    <input type='text' id='AddressType' data-bind='value: AddressType' placeholder='Home, Work, etc...' />
</label>

Now this becomes confusing. When there is four different contact types on the screen, the Label tag winds up referencing the first element with an ID of "AddressType". When I have two phone number fields on the screen, the label for the PhoneNumber field acts the same way.

How can I give unique ID names to each templated form field in a Knockout Template?

If this isn't clear, leave a comment and I will create a JSFiddle which demonstrates the issue.

Upvotes: 1

Views: 399

Answers (1)

Brandon
Brandon

Reputation: 39202

Leave off the for attribute of your label. It is optional and if not supplied, the label will apply to the child input element.

Beyond that, see this question: Unique ids in knockout.js templates

Upvotes: 2

Related Questions