When coding with JS and the DOM I find myself constantly needing to generate ids (or names) that have no purpose other than to group DOM elements together (or r
Example of working with radio labels without ID:
<div class="button-group" name="sys">
<input type="radio" value="lnx" name="radio1"> <label> Linux </label> <br>
<input type="radio" value="osx" name="radio1"> <label> OS X </label> <br>
<input type="radio" value="win" name="radio1"> <label> Windows </label>
</div>
<div class="content">
<div>Show me when 1st radio checked</div>
<div>Show me when 2nd radio checked</div>
<div>Show me when 3rdd radio checked</div>
</div>
JS
$('.button-group[name=sys] :radio').change(function(){
$(this).parent().find('label').removeClass('active');
$(this).next().addClass('active');
/* index radios vs content*/
var radioIndex=$('.button-group[name=sys] :radio').index(this);
/* hide all the content div, show one that matches radio index*/
$('.content div').hide().eq(radioIndex).show();
})
A common approach - for example in ajax calls - is to use new Date().getTime()
.
If you are worried that you might output the same id twice, you can always add a validation step:
do {uniqueID=new Date().getTime();} while (document.getElementById(uniqueID));
I agree with some of the commenters that there are probably better ways to do this, but a simple implementation of unique_id()
you could use would be:
return Math.random().toString(36);
One approach which I've used is
(function(){
var counter = 0;
window.uniqueId = function(){
return 'myid-' + counter++
}
});
then
$('.button-group').each(function (i, e) {
var name = uniqueId();
$(e).find(':radio').each(function (j, f) {
var id = uniqueId();
$(f).attr('name', name)
.attr('id', id)
.next()
.attr('for', id);
})
});