Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data-attribute to selectize.js options

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?

like image 604
yong sokheng Avatar asked Apr 09 '16 03:04

yong sokheng


People also ask

How add data attribute to select option?

HTML <option> data-* AttributeA data-* attribute on an <option> tag attaches additional data to the option item. To create a custom attribute, replace * with a lowercase string, such as data-id , data-status , or data-location .

How do you set data attribute using JS?

In order to create a new data attribute in JavaScript we just need to add a new property to the dataset object with a value. This will update the dataset object and our HTML which means our HTML will look like this.

How add data attribute in jQuery?

Basically, . data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. . attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value.

How add data attribute in HTML?

Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.


1 Answers

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>"
        }
    }
})
like image 165
t1m0n Avatar answered Oct 06 '22 02:10

t1m0n