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

时间:2017-12-28 05:36:14

标签: javascript jquery ajax jquery-select2

我有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
                });

但我无法获得option属性,知道如何为option中的所有select2设置自定义属性?

1 个答案:

答案 0 :(得分: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