简体   繁体   中英

Select2 ajax preselection with custom data value

So I have a multiselection dropdown with select2 and I fetch the info from a database. The thing is that prepopulating the dropdown with many values works with the example from the docs, but I also want to include an extra data field. This is how I try to populate the dropdown:

var productSelect = $('#product_ids');
    $.ajax({
        type: 'GET',
        url: '/ajaxOrdersData/' + orderID
    }).then(function (datas) {        
        datas.forEach(data => {
            var option = new Option(data.name, data.id, true, true);
            option.dataset.price = data.price;      
            productSelect.append(option).trigger('change');
        });     
        productSelect.trigger({
            type: 'select2:select',
            params: {
                data: datas.map(function (item) {                       
                    return {
                        text: item.nfame,
                        id: item.id,
                        price: item.price,
                    }
                })      
            }
        });
    });

The above code does create an option tag with a data-price value but then, retrieving that value like below, doesn't work:

var products = $('#product_ids').select2('data'); 

The products variable doesn't have the price data attribute.

What other ways there are for me to fetch the price data attribute of all products in multiselect when clicking on a button on the DOM?

This is a solution I came up with:

 var products =$('#product_ids option:selected'); 

And then to retrieve the value:

 $.each(products, function(index, value) {            
            actualTotals += Number(value.dataset.price);            
        }); 

An alternative solution is to keep the .select2('data'); way of fetching the selections but instead use jquery to retrieve each elements attributes from the resulting object:

var products =$('#product_ids').select2('data'); 
$.each(products, function(index, value) {            
                price = value.element.attributes['data-price'].value;         
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM