5

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.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
dokgu
  • 4,957
  • 3
  • 39
  • 77

2 Answers2

3

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')
}
dmoo
  • 1,509
  • 13
  • 16
0

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)'

Ebower
  • 33
  • 9