Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 dropdown allow new values by user when user types

The select2 component can be configured to accept new values, as ask in Select2 dropdown but allow new values by user?

And you can see it at: http://jsfiddle.net/pHSdP/646/ the code is as below:

$("#tags").select2({
    createSearchChoice: function (term, data) {
        if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    multiple: false,
    data: [{
        id: 0,
        text: 'story'
    }, {
        id: 1,
        text: 'bug'
    }, {
        id: 2,
        text: 'task'
    }]
});

The problem is that the new value is only added to the list if you enter new value and press enter, or press tab.

Is it possible to set the select2 component to accept this new value when use types and leave the select2. (Just as normal html input tag which keeps the value which you are typing when you leave it by clicking some where on the screen)

I found that the select2 has select2-blur event but I don't find a way to get this new value and add it to list?!

like image 815
Alireza Fattahi Avatar asked Sep 02 '14 05:09

Alireza Fattahi


People also ask

How do I create a Select2 dynamically?

HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.

How do you add new option if not exist in the list using Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

How do I assign a value to Select2?

How to set value to select2 in jQuery? // Set up the Select2 control $('#mySelect2'). select2({ ajax: { url: '/api/students' } }); // Fetch the preselected item, and add to the control var studentSelect = $('#mySelect2'); $. ajax({ type: 'GET', url: '/api/students/s/' + studentId }).

What is dropdownParent?

The dropdownParent option allows you to pick an alternative element for the dropdown to be appended to: $('#mySelect2').select2({ dropdownParent: $('#myModal') }); This is useful when attempting to render Select2 correctly inside of modals and other small containers.


2 Answers

Adding attribute selectOnBlur: true, seems to work for me.

Edit: glad it worked for you as well!

like image 186
Jason Avatar answered Oct 08 '22 08:10

Jason


I am using Select2 4.0.3 and had to add two options:

tags: true,
selectOnBlur: true,

This worked for me

like image 5
Char Avatar answered Oct 08 '22 08:10

Char