如何在select2中添加数据属性

时间:2016-06-13 05:11:34

标签: jquery

我有一个使用select2的脚本。

$.getJSON('/dev/api/reference?id='+ id+ '&cb='+cb, function(data){
        data = $.map(data, function(pay){
         return {id: pay.po_no, text: 'PO-'+pad(pay.po_no,8),};
        });
        $(".reference").select2({
            minimumInputLength: 1,
            multiple: false,
            data: data
        });
    });

结果是:

<select  class="reference form-control" data-width="100%" style="background-color: #faf2cc;">
    <option value="1">PO-00000001</option>
    <option value="1">PO-00000001</option>
    <option value="2">PO-00000002</option>
</select>

和我的问题,如何在选项中添加属性'data-type'?我想调用那个数据属性,我想这样:

<option value="1" data-id="1">PO-00000001</option>
<option value="1" data-id="2">PO-00000001</option>
<option value="2" data-id="3">PO-00000002</option>

1 个答案:

答案 0 :(得分:0)

$( document ).ready(function() {
 var i = 1;
 $(".reference > option").each(function() { // iterate through all options of selectbox
    $(this).attr('data-id',i); // add attribute to option with value of i
    i++; // increment i
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select  class="reference form-control" data-width="100%" style="background-color: #faf2cc;">
    <option value="1">PO-00000001</option>
    <option value="1">PO-00000001</option>
    <option value="2">PO-00000002</option>
</select>