Add data-attribute to selectize.js options

2019-05-14 16:05发布

问题:

I am using selectize.js for my project. But I have problems with data-attributes. I want to add data-attributes to the select options. I have default select like this:

<option data-open-balance="false" selected="selected" value="1">PNP.SI.080416</option>

But When I add selectize to this select, it becomes:

<div data-value="1" data-selectable="" class="selected">PNP.SI.080416</div>

I see that its "item object" only get value, and text. So, how can I add other data-attributes to its item object?

回答1:

I've looked at docs and they say that if you want to add custom attributes to your elements, you should use dataAttr option, by default it data-data. So in your case code will look somethnig like this:

HTML

<select>
    <option data-data='{"openBalance": true}' selected="selected" value="1">PNP.SI.080416</option>
</select>

JS

Here we provide custom render method to draw options with attributes we need:

$('select').selectize({
    render: {
        option: function (data, escape) {
            return "<div data-open-balance='" + data.openBalance + "'>" + data.text + "</div>"
        }
    }
})