Skip to content Skip to sidebar Skip to footer

Using Auto Generated (ie Random) Ids In Html Forms

I'm creating a form from various complex controls that I have built as Backbone views. Understandably I want to reliably link the labels to the elements, which I am d

Solution 1:

There's nothing bad in auto-generating IDs. If they have not to be human- (== developer) readable, you can go crazy there. Create a simple function, that spits out unique strings, and there you go:

functiongenerateId() {
    return'GENERATED_ID_' + (++generateId.counter);
}
generateId.counter = 0;

id = generateId();
html = '<label for="'+id+'">Foo</label> <input id="'+id+'">';

Nothing bad happening here.

(Of course, if you could nest the input in the label, that would be a wee bit nicer.)

Solution 2:

I would use the cid attribute of the Backbone view. This is already unique. Probably then override _.template in a base view to always include this (to save passing in each time).

Post a Comment for "Using Auto Generated (ie Random) Ids In Html Forms"