Created
May 27, 2011 04:49
-
-
Save farinspace/994658 to your computer and use it in GitHub Desktop.
Repeating fields Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// disable all fields in a template (so they do not get submitted) | |
$('.template').find('input, textarea, select, button').each(function() | |
{ | |
$(this).attr('disabled', 'disabled'); | |
}); | |
function doRepeat(replace) | |
{ | |
var container = $(this).closest('.container'); | |
var collection = $('> .collection', container); | |
var template = $('> .template', collection); | |
var clone = template.clone().removeClass('template'); | |
var pos = findPos($("[name*='[']", template).attr('name'), replace); | |
var the_index = -1; | |
$("[name*='[']", collection).each(function() | |
{ | |
var the_name = $(this).attr('name'); | |
if (undefined != the_name && '' != the_name) | |
{ | |
var parts = the_name.split('['); | |
the_index = Math.max(the_index, ! isNaN(parseInt(parts[pos]))?parseInt(parts[pos]):-1); | |
} | |
}); | |
clone.find('input, textarea, select, button').each(function() | |
{ | |
if ( ! $(this).parents('.template').length) | |
{ | |
$(this).removeAttr('disabled'); | |
} | |
var the_name = $(this).attr('name'); | |
if (undefined != the_name && '' != the_name) | |
{ | |
var parts = the_name.split('['); | |
parts[pos] = (the_index + 1) + ']'; | |
the_name = parts.join('['); | |
$(this).attr('name', the_name); | |
} | |
}); | |
collection.append(clone); | |
clone.show(); | |
} | |
function findPos(n, c) | |
{ | |
var p = n.split('['); | |
var pos; | |
$.each(p, function(i, v) | |
{ | |
pos = i; | |
if (v.indexOf(c) > -1) | |
{ | |
return false; | |
} | |
}); | |
return pos; | |
} | |
$('.qadd').live('click', function(e) | |
{ | |
e.preventDefault(); | |
doRepeat.call(this, '%'); | |
}); | |
$('.oadd').live('click', function(e) | |
{ | |
e.preventDefault(); | |
doRepeat.call(this, '@'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment