jquery - How to append data into existing Select2

10,395

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

select2_data.push({ id: 4, product_text: 'text_4' });
Share:
10,395
technology_dreamer
Author by

technology_dreamer

Updated on June 23, 2022

Comments

  • technology_dreamer
    technology_dreamer almost 2 years

    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

  • technology_dreamer
    technology_dreamer about 10 years
    It's not possible..it returns this error: Uncaught TypeError: Cannot call method 'append' of null
  • 76484
    76484 about 10 years
    Don't use 'append', use 'push'. And call it on 'select2_data', an object which is most definitely not null (unless you secretly nullified it elsewhere).
  • technology_dreamer
    technology_dreamer about 10 years
    Ohh I got it...well my problem is I tried to call it using another function but your solution will solve it quickly..thanks