Fomantic-UI
Fomantic-UI copied to clipboard
[dropdown] How can i set custom data in options when i dynamic generate options?
Help Wanted
When options are dynamically generated, how to set custom data(like <option value='...' data-id='...'>...</option>) in it?
Problem
I want the dropdown to dynamic generate options by the user input. For example: when user input a, the dropdown should display a1,a2,a3... , when user input b, the dropdown should display b1, b2, b3 ... . so i set this,
{
sortSelect: true,
fullTextSearch: 'exact',
on: 'hover',
allowAdditions: true,
clearable: true,
forceSelection: false
}
//
$('input').on('input', function() {
let v = $(this).val();
$(this)
.dropdown('change values', [
{ name: v + '1', value: v + '1'},
{ name: v + '2', value: v + '2'},
{ name: v + '3', value: v + '3'}
]);
});
it's fine. but now i need to add my custom data to the options When they are dynamically generated, because other field's value may depend on this choosen option's id. something like this
$('input').on('input', function() {
let v = $(this).val();
$(this)
.dropdown('change values', [
{ name: v + '1', value: v + '1', data-id: '...'},
{ name: v + '2', value: v + '2', data-id: '...'},
{ name: v + '3', value: v + '3', data-id: '...'}
]);
});
it's not work. so, how can i set my own data to the option element?
Maybe something like that :
$('input').on('input', function() {
let v = $(this).val();
let itemSelector = $(this).dropdown("setting", "selector").item;
$(this)
.dropdown('change values', [
{ name: v + '1', value: v + '1', data-id: '...'},
{ name: v + '2', value: v + '2', data-id: '...'},
{ name: v + '3', value: v + '3', data-id: '...'}
])
.find(itemSelector).data('id', '...');
});
Note JQuery doc : Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.
If I understand the question correctly this isn't easily possible however I think we could add something to easily do this.
@fomantic/maintainers In the templates.menu function we could get all properties from the values object which are data-* and add them to the menu item. This would allow users to specify any data- attribute and add it to option items. We would have to filter out data-value and data-text so they can't override them.
@hammy2899 Thanks, you understand correctly. All I want is to add custom properties when dynamically generating the content of the Dropdown.
Implemented by #3004