Skip to content

Instantly share code, notes, and snippets.

@johnReeve
Created December 4, 2012 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnReeve/4206643 to your computer and use it in GitHub Desktop.
Save johnReeve/4206643 to your computer and use it in GitHub Desktop.
A bit of javascript to add arbitrary elements to a list (in this case of input elements for an array)
<script>
(function($) {
$(document).ready(function (){
// here we can add <li><button class="addNewSiblingField">Add New</button></li>, and it will auto setup a list to add and remove arbitrary elements
$('.addNewSiblingField').closest('ul').addClass('addNewSiblingsList');
$('.addNewSiblingField').parent().siblings().append('<button class="removeSiblingField">Remove</button>');
$('.addNewSiblingsList').on('click', '.addNewSiblingField', function(e){
var newField = "";
e.preventDefault();
newField = $(this).parent().prev().clone();
$('input', newField).val('');
$(this).parent().before(newField);
});
// and this sets up the "delete" function:
$('.addNewSiblingsList').on('click', '.removeSiblingField', function(e){
$(this).parent().remove();
});
});
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment