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 <input> elements, which I am doing with the normal for attribute.
However, sometimes I need to use the same control multiple times. I am using data attributes to drive the form, so I do not need the id attribute for my own use, and can use classes to identify each control.
Therefore, I am considering whether it makes sense to generate random ids, just to link the <label> and <input> together? This seems a really bad idea, but I am unsure there is a better one?
I can't just put the <input> inside the <label>, as they have to be separate from each other.
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:
function generateId() {
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.)
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).
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