Search code examples
jqueryjquery-select2ui-select2

JQuery Select2 Item not found trigger


I would like to have a callback for my select2 fields. I'm trying to display all the item name on my select2 component. But if the user just typed in the name of the item and the item is not under any option of the select input then I would like to pop up a dialog informing them if they want to add this as new item. So I was wondering if there are any sort of callback for this function. Here's what I was thinking

$('select').select2({
    onSelect: function(item) {
         if (item == null || $(this).options == 0) {
         // A dialog will prompt saying would you like to add this item?
         }
    }
});

I know syntax for this is not correct but you can the idea right? I just want to know what is the callback to determine if an item type in the select2 is not existing or better yet I want a callback to be triggered if the user type in something that is not on the select2 options.


Solution

  • Ok here you go. Below are the 2 scenarios which works to some extent:

    Scenario 1:

    DEMO

    Enabled confirmation prompt only for click on the newtag

    $('.select2').select2({
        tags: true,
        tokenSeparators: [",", " "],
        createTag: function (tag) {
            return {
                id: tag.term,
                text: tag.term,
                isNew : true
            };
        }
    }).on("select2:select", function(e) {
        if(e.params.data.isNew){
            var r = confirm("do you want to create a tag?");
            if (r == true) {
    $(this).find('[value="'+e.params.data.id+'"]').replaceWith('<option selected value="'+e.params.data.id+'">'+e.params.data.text+'</option>');
            }
            else
            {
                $('.select2-selection__choice:last').remove();
                $('.select2-search__field').val(e.params.data.text).focus()
            }
        }
    
    });
    

    Scenario 2:

    DEMO

    Confirmation for both click and space but tag gets added to list:

    $('.select2').select2({
        tags: true,
        tokenSeparators: [",", " "]
    }).on("change", function(e) {
        var isNew = $(this).find('[data-select2-tag="true"]');
        if(isNew.length){
            var r = confirm("do you want to create a tag?");
            if (r == true) {
    isNew.replaceWith('<option selected value="'+isNew.val()+'">'+isNew.val()+'</option>');        
            }
            else
            {
                $('.select2-selection__choice:last').remove();
                $('.select2-search__field').val(isNew.val()).focus()
            }
        }
    });
    

    You need to find some workaround for tag getting added in false case.