Frage

After some research through several stackoverflow solutions, none of them helped my to solve this problem.

I have an initial data to populate a select2's input:

var select2_data = [{id:0, product_text:'text_1'},{id:1,product_text:'text_2'},{id:2, product_text:'text_3'}];

Then select2 is initiated without any problem.

var select2 = $('#select2_id').select2(
{
   id: function(e) {return e.product_text; },
   data:{results: select2_data, text:'product_text'},
       width: '50%',
   placeholder: 'Choose a product', 
   formatSelection: Product_Result,
   formatResult: Product_Result 
});

But my problem is I don't know how to append new data to this existing select2's input.

New data example:

var new_data = {id:4, product_text: 'text_4'};

I made some experiments trying to obtain the existing data and append into the existing data array like this:

var select2_existing_data = $('#select2_id').select2('data');
select2_existing_data.append(new_data);

But after some research this select2_existing_data variable is proper to returns just the selected data, not the entire data.

Hope you can help me to find the solution, Thanks

War es hilfreich?

Lösung

Is it not as simple as just appending to the original data array?

select2_data.push({ id: 4, product_text: 'text_4' });

Andere Tipps

I did something like this a while back...

//get the current data array (what is currently in the select 2)
var dataArray = $("#myselect2").select2('data');

//push your additional item
dataArray.push({ "Name": 'MyNewItem', "Id": 'MyNewItemId' });

//push new item with items that were already in the list
$("#myselect2").select2("data", dataArray);

Not tested. You might want to check select2('data') has items in it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top