0
votes

Background Info:

To start, I create a input text field, a "add" button, and a select2 menu with dummy data. When the user types in something to the input text field and clicks add, this item is then added to the select2 data.

To do this, I had to destroy the select2 menu, then recreate it with the added data. I haven't found a way to add objects to the data and refresh the select2 menu, and based on research, this is a common way to do this...

function addToSel2(text){
    console.log(text);
    $("#selectbox").select2("destroy");
    startdata.push({id:text,text:text});
    createSel2(startdata);
}

On the select2-opening event, I prevent the default action (that is opening) so that the user is unable to open the select2 menu (because they have not entered any data).

$("#selectbox").select2({
    data: {id: 0,text: 'name'},
    placeholder: "add an item!",
}).on('select2-opening', function(e){
    e.preventDefault();
}); 

Problem:

Once the user adds the first (and every one after) value to the select2 menu, the placeholder changes, so I know that a NEW select2 menu has been created, however the user is still unable to open the menu. It is as if the preventDefault is still affecting the new select2 menu....

Attempts at a solution

I have tried "return false" on the initial select2 menu event, and "return true" on the select2 menus that contain data thereafter, and have found similar results.

Here is a jsfiddle that represents my issue. http://jsfiddle.net/z6n5C/

1

1 Answers

0
votes

unbind event using .off():

DEMO

if(data.length > 0)
    {
        $("#selectbox").select2({
            data: data,
            placeholder: "Select item...",
            allowClear: true
        }).off('select2-opening');
    }