Add data-attribute to selectize.js options
Asked Answered
Q

1

6

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?

Quake answered 9/4, 2016 at 3:50 Comment(0)
B
14

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>"
        }
    }
})
Barra answered 9/4, 2016 at 7:37 Comment(3)
If someone want to use php can use this <option data-data='<?php echo json_encode( $your_option ); ?>' value='<?php echo $value; ?>'><?php echo $text; ?></option>. It's very important the use of single quote ' in data-data tag, because JSON use double quote " for the structure.Libertinism
Downvoted because the JS solution is subject to XSS. If the data.text contains html tags or simple > it will break the dropdown. For this escape function is provided such that you can escape data before returning them. The resulting return should be: return "<div data-open-balance='" + escape(data.openBalance) + "'>" + escape(data.text) + "</div>"Biblical
@Biblical although, in my opinion, it was not related to question, I've updated my answer with your notes, thanks.Barra

© 2022 - 2024 — McMap. All rights reserved.