最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using auto generated (ie random) IDs in HTML forms - Stack Overflow

programmeradmin2浏览0评论

I'm creating a form from various plex 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.

I'm creating a form from various plex 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.

Share Improve this question asked Nov 21, 2013 at 10:36 Kirk NorthropKirk Northrop 832 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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).

发布评论

评论列表(0)

  1. 暂无评论