Last active
November 4, 2020 08:04
-
-
Save ngekoding/d3bbd99acd749d04361abdbcc0dad6f2 to your computer and use it in GitHub Desktop.
Duplicating jQuery Select2 (supporting add & delete)
This file contains 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
<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> |
This file contains 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
$(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'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here the preview