0
votes

I have this code of Jexel with Select2 where I load the default values for each jexcel row from an array and use select2 for the dropdown: https://jsfiddle.net/ktumw528/

However I wish to know how can I populate the options from select2 with the values from var data? Also how can I add new country to the select2 dropdown if not found when typing.

var data = [
    ['Spain'],
    ['France'],
    ['Germany'],
];

var customDropDown1 = {
    // Methods
    closeEditor : function(cell, save) {
        // Get value
        var txt = $(cell).find('.editor').val();

        // Set visual value
        $(cell).html(txt);

        // Close edition
        $(cell).removeClass('edition');

        // Save history
        return txt;
    },
    openEditor : function(cell) {
        // Get current content
        var currentValue = $(cell).text();

        // Create the editor
        var editor = document.createElement('select');
        $(cell).html(editor);
        $(editor).prop('class', 'editor');
        $(editor).html('<option>Brazil</option><option>Canada</option>')
        $(editor).val(currentValue);
        // Create the instance of the plugin
        $(editor).select2().on('select2-blur', function() {
            $('#' + $.fn.jexcel.current).jexcel('closeEditor', $(cell), true);
        });
    },

    getValue : function(cell) {
        return $(cell).text();
    },
    setValue : function(cell, value) {
        $(cell).html(value);

        return true;
    }
}

$('#my').jexcel({
    data:data,
    columns: [ { editor:customDropDown1 } ],
    colHeaders: ['Country'],
    colWidths: [ 300 ]
});

Any tips are welcomed :) thanks a lot!

1

1 Answers

0
votes

I think you can use last version of JExcel (v4). You will have more options and more option editor.

With this new version, you can create editor with set custom value. And you have an option for dropdown for add new item https://bossanova.uk/jexcel/v4/examples/dropdown-and-autocomplete

and this documentation : https://bossanova.uk/jsuites/dropdown-and-autocomplete/new-options

Example :

<script>
var data5 = [
    [1, 'Beatles'],
    [2, 'Beatles'],
    [3, 'Beatles'],
    [4, 'Beatles'],
];
 
jexcel(document.getElementById('spreadsheet5'), {
    data: data5,
    columns: [
        {
            type: 'dropdown',
            title: 'Name',
            width: '300px',
            source: [
                { id:'1', name:'Paul' },
                { id:'2', name:'Ringo' },
                { id:'3', name:'George' },
                { id:'4', name:'John' },
            ],
            options: { newOptions: true } // Option for add new options
        },
        {
            type:'dropdown',
            title:'Band',
            width:'200px',
            source: ['Beatles'],
        },
    ],
});
<script>

otherwise if you want keep v2, i suggest use external source on var, and add new item on this variable. Because the editor is created only on open cell.