Skip to content

Instantly share code, notes, and snippets.

@floriankrueger
Created September 21, 2011 15:26
Show Gist options
  • Save floriankrueger/1232365 to your computer and use it in GitHub Desktop.
Save floriankrueger/1232365 to your computer and use it in GitHub Desktop.
add/remove form element with jQuery
$(document).ready () ->
# RECIPE_CREATION_FORM
if $('#recipe_create_form').length > 0
# make tags field a tags field
$('#recipe_tags').tagsInput
#autocomplete_url : url_to_autocomplete_api
#autocomplete_url :
# option : value
# option : value
height : '100px'
width : '98%'
interactive : true
defaultText : 'add a tag'
#onAddTag : callback_function
#onRemoveTag : callback_function
#onChange : callback_function
removeWithBackspace : true
minChars : 3
#maxChars : 0 #if not provided there is no limit,
placeholderColor : '#666666'
# declare dynamic-forms functions
sectionIngredients =
c : 0
min : 1
container : 'ingredients'
build : () ->
"<p class='ingredient' id='recipe_ingredients_#{this.c}'>
<input type='text' id='recipe_ingredients_#{this.c}_amount' name='recipe[ingredients][#{this.c}][amount]' class='amount' />
<input type='text' id='recipe_ingredients_#{this.c}_measure' name='recipe[ingredients][#{this.c}][measure]' class='measure' />
<input type='text' id='recipe_ingredients_#{this.c}_name' name='recipe[ingredients][#{this.c}][name]' class='name' />
</p>"
lastElemId: () ->
"recipe_ingredients_#{this.c-1}"
sectionSteps =
c : 0
min : 1
container : 'steps'
build : () ->
"<p class='step' id='recipe_steps_#{this.c}_container'>
<label for='recipe_steps_#{this.c}'>Step #{this.c+1}</label>
<textarea id='recipe_steps_#{this.c}' name='recipe[steps][#{this.c}]' class='step'></textarea>
</p>"
lastElemId: () ->
"recipe_steps_#{this.c-1}_container"
sections =
ingredients: sectionIngredients
steps: sectionSteps
dynFormAdd = (section) ->
$('#' + sections[section].container).append(sections[section].build())
sections[section].c++
dynFormRemove = (section) ->
if sections[section].c > sections[section].min
$('#' + sections[section].lastElemId()).remove()
sections[section].c--
# add the first elements
dynFormAdd('ingredients')
dynFormAdd('steps')
# hook up events
$('#recipe_ingredients_add').click ->
dynFormAdd('ingredients')
$('#recipe_ingredients_remove').click ->
dynFormRemove('ingredients')
$('#recipe_steps_add').click ->
dynFormAdd('steps')
$('#recipe_steps_remove').click ->
dynFormRemove('steps')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment