-
-
Save arcanoix/9a07d86ebc2b679818127ad1459dd7dd to your computer and use it in GitHub Desktop.
Elementos dinámicos con jquery(Boton de agregar y eliminar los elementos)
This file contains hidden or 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
$.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