Skip to content

Instantly share code, notes, and snippets.

@elib0
Created May 4, 2016 19:38
Show Gist options
  • Save elib0/8f18dd4c6bae4c856102346ecff1e73e to your computer and use it in GitHub Desktop.
Save elib0/8f18dd4c6bae4c856102346ecff1e73e to your computer and use it in GitHub Desktop.
Elementos dinámicos con jquery(Boton de agregar y eliminar los elementos)
$.on('click','.dinamic .add',function(e){
/* Elementos dinamicos. Solo es necesario agregar las clases dinamic, add y remove,
como se muestra en el ejemplo a continuacion:
<div class="dinamic">(contenedor)
<div>(elemento inicial)
<input/>
<button type="button" class="add">agregar</button>
</div>
<script class="template" type="text/x-jquery-tmpl">(plantilla de nuevo elemento)
<div>
<input/>
<button type="button" class="remove">remover</button>
</div>
</script>
<div class="template">(plantilla alternativa)
<input/>
<button type="button" class="remove">remover</button>
</div>
</div>
*/
//agregar elemento dinamico
var template=$(this).closest('.dinamic').find('.template')[0],
$form=$(this).closest('form'),
$new=template.nodeName=='SCRIPT'?$(template).tmpl():$(template).clone().removeClass('template');
$new.addClass('element').insertBefore(template);
$new.find('[disabled]').prop('disabled',false);
if($.fn.validator&&$form.data('bs.validator')) $form.validator('reloadFields');
if($.fn.formValidation&&$form.data('formValidation')){
$new.find('input,textarea,select').filter(':visible').each(function(){
$form.formValidation('addField',this.name);
});
}
}).on('click','.dinamic .element .remove',function(e){
//remover elemento dinamico
$(this).closest('.element').fadeOut(250,function(e){
$(this).prev().find('select,input,textarea,button').last().focus();
$(this).remove();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment