Semantic UI Dropdown Option Data Attribute

3k Views Asked by At

I've been trying to attach a data-* attribute in a Semantic UI dropdown option but to no success (the data attributes are not being copied to the resulting dropdown options).

Here's the structure of my select:

HTML

<select id='my-dropdown' name='department'>
    <option value='1' data-wsg='something'>Department 1</option>
    <option value='2' data-wsg='another'>Department 2</option>
    . . .
    <option value='n' data-wsg='custom data'>Department N</option>
</select>

jQuery

$("#my-dropdown").dropdown({
    allowAdditions: false,
    fullTextSearch: true,
    onHide: function() {
        // Some codes.
    },
    onChange: function(value, text, choice) {
        // Access the data-wsg attribute of the selected option.
    }
});

I've been reading around a bit but all I saw regarding data attribute support was storing the settings in there. Not really what I need.

Hopefully someone has done something similar and let me know what the solution is.

2

There are 2 best solutions below

0
On

Its not pretty, but you can use the details in the onChange to hunt down the data attribute. The functionality you are after was specifically rejected here - https://github.com/Semantic-Org/Semantic-UI/issues/931

onChange: function(value, text, choice) {
    $(this).children('option[value=' + $(choice).data('value') + ']').data('wsg')
}
0
On

I was able to get this to work pretty consistently by attaching a data attribute to the main dropdown object, then just going two more levels to get the selection I want, like this

'[data-testid="region-dropdown"] > div.visible.menu.transition > div:nth-child(4)'

Semantic UI wraps all the dropdown options in a div with the visible.menu.transition class and then each option is it's own div, so the nth-child lets you select a specific option as long as the order of your options is consistent.

I've found this works with pretty much any input type, it's just a matter of figuring out where to set the data attribute, then finding the path to the selector past that.

For example, a specific tab can be selected with something like

'[data-testid="tabs-menu"] > div.ui.attached.tabular.menu > a:nth-child(1)'