Skip to content

Instantly share code, notes, and snippets.

@paul
Created October 8, 2010 17:39
Show Gist options
  • Save paul/617180 to your computer and use it in GitHub Desktop.
Save paul/617180 to your computer and use it in GitHub Desktop.
/*
* Correct field names and ids (and for) so forms work and labels
* line up. Replaces names like:
*
* post[author][42][name]
* post[author][][name]
*
* with a timestamp, so that there's no collisions.
*
* post[author][1283896010739][name]
*
* does the same with id attributes, of the form
*
* post_author_42_name
*
*/
function fixFieldNames(fields, prefix) {
esc_prefix = XRegExp.escape(prefix);
var ts = new Date();
ts = ts.getTime();
var old_name = XRegExp("^" + esc_prefix + "\\[\\d*\\](.*)$");
var new_name = prefix + "[" + ts + "]$1";
var id_prefix = name2id(prefix);
var old_id = XRegExp("^" + id_prefix + "_\\d*(.*)$");
var new_id = id_prefix + "_" + ts + "$1";
$(fields).find('label, input, select, textarea').each(function(i, el) {
$el = $(el);
if($el.attr('for') && $el.attr('for').match(old_id)) {
$el.attr('for', $el.attr('for').replace(old_id, new_id));
}
if ($el.attr('name') && $el.attr('name').match(old_name)) {
$el.attr('name', $el.attr('name').replace(old_name, new_name));
}
if ($el.attr('id') && $el.attr('id').match(old_id)) {
$el.attr('id', $el.attr('id').replace(old_id, new_id));
}
});
}
/*
* Changes values and selected of all form elements to empty
*/
function resetFields(fields) {
$(fields).find('input,select,textarea').each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = 0;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment