Skip to content

Instantly share code, notes, and snippets.

@dgalarza
Created October 2, 2012 14:22
Show Gist options
  • Save dgalarza/3819513 to your computer and use it in GitHub Desktop.
Save dgalarza/3819513 to your computer and use it in GitHub Desktop.
Dynamic Rails Form
// -- This method adds a field to the form:
var addField = function(target){
// -- get handle on relevant fieldset container and clone it:
var fieldset = target.parent().parent().find('div.item-fields').last();
var new_fieldset = fieldset.clone();
// -- Add flag to show that field was dynamically built by the front end
// -- and show fieldset if the original was hidden:
new_fieldset.addClass("new-dynamic-field").show();
new_fieldset.find("input.placeholder-activated").removeClass("placeholder-activated");
new_fieldset.find("span.forced-placeholder").remove();
new_fieldset.find("input.email-activated").removeClass("email-activated");
// -- Clear out inputs:
new_fieldset.find('input').val('');
// -- Update id and name attributes:
var timestamp = (new Date).valueOf();
var child, child_id, child_name;
var children_needing_id_change = new_fieldset.find("li, input, select");
for(var i=0; i<children_needing_id_change.length; i++){
child = $(children_needing_id_change[i]);
child_id = child.attr('id') || "";
child_name = child.attr('name') || "";
if(child_id.length > 0){
child_id = child_id.replace(/attributes_[0-9]*/, "attributes_"+timestamp);
child.attr('id', child_id);
}
if(child_name.length > 0){
child_name = child_name.replace(/\[[0-9]*\]/, "["+timestamp+"]");
child.attr('name', child_name);
}
}
// -- Drop new fieldset back into the dom:
fieldset.after(new_fieldset);
// -- Enable placeholder/email validation for the new elements:
enable_placeholder_text_for_inputs();
enable_email_inputs();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment