unique identifiers after clone

unique identifiers after clone


This method makes the 'id' and 'name' attributes unique, which is very
useful after cloning. It updates 'for' attributes in 'label' tags as
well. The 'for' and 'id' will continue to match and, if 'id' and
'name' are the same (common in form field elements and anchor tags).
jQuery.fn.extend({
    // Correct uniqueness for all id attributes and assoc labels.
    // Correct uniqueness for all name attributes.
    makeIdentifiersUnique: function(makeUnique)
    // makeUnique: (optional) returns unique identifier given an
identifier (string)
    {
        var descendantOrSelf = this.find("*").andSelf();
        var strUniqueSuffix = Math.floor(Math.random() *
1679616).toString(36); // 4 digit alphanum
        makeUnique = ("function" == typeof makeUnique ? makeUnique :
function(id)
        {
            // Remove suffix of "_" 4-digit-alphanum (if it exists), then
append new suffix
            return id.replace(/_[0-9a-z]{4}$/,"") + "_" + strUniqueSuffix;
        });
        descendantOrSelf.filter("[id]").each(function()
        {
            this.id = makeUnique(this.id);
        });
        descendantOrSelf.filter("label").each(function()
        {
            this.htmlFor = makeUnique(this.htmlFor);
        });
        // caution: do not split id & name uniqueness code b/c for <a>, id
should equal name,
        // which won't be the case if the .random() function is called
twice.
        descendantOrSelf.filter("[name]").each(function()
        {
            try
            {
                if (jQuery.browser.msie)
                {
                    // Microsoft JScript allows the name to be changed at run time.
                    // HOWEVER!
                    // This does not cause the name in the programming model to
change
                    // in the collection of elements, but it does change the name
used
                    // for submitting elements. The NAME attribute cannot be set at
run time
                    // on elements dynamically created with the createElement
method.
                    // To create an element with a name attribute, include the
attribute
                    // and value when using the createElement method.
                    var strHTML = this.outerHTML + "";
                    strHTML = strHTML.replace(new RegExp("name=" + this.name, "g"),
"name=" + makeUnique(this.name));
                    jQuery(this).replaceWith(strHTML);
                }
                else
                {
                    this.name = makeUnique(this.name);
                }
            }
            catch (ex)
            {
                // ignore
            };
        });
        return this;
    }
});
Please consider adding this to the jQuery library.