Add data-attribute to selectize.js options

前端 未结 1 432
后悔当初
后悔当初 2021-01-13 01:58

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:

相关标签:
1条回答
  • 2021-01-13 02:12

    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>"
            }
        }
    })
    

    UDATE

    As Kyborek notes that in order to secure your site or web app from XSS, you should use escape method in render callback. Also use it if you want to display html tags in data.text. Updated example will look something like this:

    $('select').selectize({
        render: {
            option: function (data, escape) {
                return "<div data-open-balance='" + escape(data.openBalance) + "'>" + escape(data.text) + "</div>"
            }
        }
    })
    
    0 讨论(0)
提交回复
热议问题