Select2, search and add button, how to implement exact search and add button output if there is no option?

  • 0
    Hello everyone.
    In general, there was such a problem, I added a button in the select, I display the items in the select from the database table, if there is no item, let's say I enter 111, if it is not there, then the add button appears and I can add to the database table directly from the search for a field in the select. br />
    What is the problem, let's say I have options that display, 11111111 and 1111111111, these are all examples, and I want to add, let's say 111, but I don't see the add button, since the live search shows me items 11111111 and 1111111111, it turns out that I need Somehow to make an exact search, if there is no such name (111) in the table, then there was an add button. otherwise he finds something that can be suitable for selection and does not display the button.

    Off site select2 https://select2.org

    Screen to make it clearly understandable: (there is no option 111, but there is no add button either).


    And if there is no option and nothing suitable for selection, then there is a button.


    Not all code, but I think the meaning is clear.
    MMKTC.actions.getBrands();
    	MMKTC.selectors.brands = $('.js-example-basic-single#namebrand').select2({
    		allowClear: true,
    		escapeMarkup: function(markup) {
    			return markup; 
    		},
    		placeholder: "Поиск марки",
    		language: {
    		noResults: function () {
    				return '<span class="select2-btn act-addbrand">Добавить</span>';
    			}
    		}
        });
    	$(document).on('click', '.select2-container .act-addbrand', function(e) {
    		e.preventDefault();
    		let container = $(this).closest('.select2-container');
    		let name = container.find('.select2-search__field').val();
    		let formLoad = new FormData();
    		formLoad.append('name', name);
    		MMKTC.actions.addBrand(formLoad, function(id){
    			$('.js-example-basic-single#namebrand').select2('close');
    			MMKTC.selectors.brands.val(id).trigger("change");
    		});
    	});
    	});
    JavaScript Cole Foster, Sep 7, 2019

  • 0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!