Skip to content

Instantly share code, notes, and snippets.

@brettbuddin
Created November 20, 2009 14:58
Show Gist options
  • Save brettbuddin/239547 to your computer and use it in GitHub Desktop.
Save brettbuddin/239547 to your computer and use it in GitHub Desktop.
Duplicates a group of form fields and makes their attributes unique (great for nested_attributes in Rails)
jQuery.fn.make_attr_unique = function(attr) {
var value = $(this).attr(attr);
if (value !== undefined) {
var value_pieces = value.split(/[0-9]+/);
if (value_pieces.length > 1) {
$(this).attr(attr, value_pieces[0] + Number(new Date()) + value_pieces[1]);
}
}
};
jQuery.fn.clone_fields_unique = function() {
var clone = $(this).clone(false);
clone.find('textarea,input,label').each(function() {
$(this).make_attr_unique('id');
$(this).make_attr_unique('name');
$(this).make_attr_unique('for');
});
return clone;
};
$('.snippet').clone_fields_unique().appendTo('.snippets');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment