select2为每个选项手动设置选项属性

问题描述 投票:1回答:1

我有select2下拉列表:

 <select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />

我正在通过dropdown调用设置ajax数据,如:

   $.ajax({
    type: "POST",
    url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
    data: '{LedgerId: "' + AccId + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        if (data.d.Result == "OK") {
            var challanresults = [];
            $.each(data.d.Records, function (index, challn) {
                challanresults.push({
                    id: challn.MaterialSheet_ID,
                    text: challn.Challan_No,
                    Amount: challn.Total_Amount
                });
            });

            eachtr.find('.txtSelectChallan').select2({
                placeholder: "Select Challan",
                data: challanresults,
                multiple: true
            });
            swal.close();
            challanresults = null;
        }
    },
    error: function (err) {
        swal(
           'Oops...',
           'Error occured while retrieving data',
           'error'
         );
    }
});

我得到dropdown像:

<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
  <option value="1006">123123</option>
  <option value="1007">32123</option>

我试图使用以下方法设置option属性:

             challanresults.push({
                    id: challn.MaterialSheet_ID,
                    text: challn.Challan_No,
                    Amount: challn.Total_Amount
                });

但我不能得到amout因为option属于任何想法如何为option中的所有select2设置自定义属性?

javascript jquery ajax jquery-select2
1个回答
1
投票

在foreach循环中尝试这样,然后设置触发器。

var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};

var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');

Check this link for further solution on custom attributes

或者,您可以在结果集var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>的循环中执行此操作

这就是Select2官方网站对自定义数据字段的看法

$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});

// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');

Click here for the above reference link

© www.soinside.com 2019 - 2024. All rights reserved.