Skip to content

Instantly share code, notes, and snippets.

@ngekoding
Last active November 4, 2020 08:04
Show Gist options
  • Save ngekoding/d3bbd99acd749d04361abdbcc0dad6f2 to your computer and use it in GitHub Desktop.
Save ngekoding/d3bbd99acd749d04361abdbcc0dad6f2 to your computer and use it in GitHub Desktop.
Duplicating jQuery Select2 (supporting add & delete)
<div class="row expert-wrap">
<div class="col-md-6 form-group">
<input type="text" id="expert-field_1" class="form-control" name="expert-field[]" placeholder="Misal: Ahli Teknik Sipil">
</div>
<div class="col-md-6 expert-name-wrap">
<div class="form-group">
<select name="expert-name[]" id="expert-name_1" class="form-control select2">
<option value=""></option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div class="action-wrap">
<i class="fa fa-trash text-danger cursor-pointer btn-delete d-none"></i>
<i class="fa fa-plus text-success cursor-pointer btn-add ml-2"></i>
</div>
</div>
</div>
$(document).on('click', '.expert-wrap .action-wrap .btn-add', function() {
var template = $('.expert-wrap').last().clone();
var idNum = parseInt($('.expert-wrap').last().find('[id]:first').prop('id').split('_')[1]);
template.find('[id]').each(function() {
$(this).prop('id', $(this).prop('id').split('_')[0] + '_' + (idNum + 1));
});
template.find('input').val('');
template.find('select').val('');
template.find('.select2-container').remove();
template.find('[data-select2-id]').removeAttr('data-select2-id');
template.find('.select2').select2({
placeholder: 'Silahkan pilih',
allowClear: true,
width: 'resolve'
});
$('.expert-wrap').last().after(template);
$('.expert-wrap').not(':last').find('.btn-add').addClass('d-none');
$('.expert-wrap').find('.btn-delete').removeClass('d-none');
}).on('click', '.expert-wrap .action-wrap .btn-delete', function() {
$(this).parents('.expert-wrap').remove();
$('.expert-wrap').last().find('.btn-add').removeClass('d-none');
var num = $('.expert-wrap').length;
if (num == 1) {
$('.expert-wrap').first().find('.btn-delete').addClass('d-none');
} else {
$('.expert-wrap').first().find('.btn-delete').removeClass('d-none');
}
});
@ngekoding
Copy link
Author

ngekoding commented Nov 4, 2020

Here the preview

Select2 Clone by Ngekoding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment