Score:0

Set value in a choices.js dropdown after it's been created

gf flag

Using Drupal 9.4 and choices.js 10.2 (design required a highly styled dropdown that I couldn't do with a standard element). The choices dropdown is created by a view.

When I had the plain select item in place, I could use javascript to set an optional default value for one of the two dropdowns. However, with the choices.js dropdown, I haven't found a simple way to make that happen despite scouring the github and stack overflow.

in my JS, I have tried:

var $org = '{{ org_id }}';
$id = "#fcs-{{ paragraph.id() }} #edit-field-audience-target-id";
const dropdown = new Choices(document.querySelector($id));
dropdown.setChoiceByValue($org);

However, the console tells me: "choices.min.js?rqlz1t:2 Trying to initialise Choices on element already initialised". I was hoping there was another method where I can tap into an existing Choices instance and call setChoiceByValue('x').

I might be able to do everything manually, but I want to make sure I'm not missing something.

Score:0
mg flag

You can set a selected: true property on the item you want to be auto-selected.

[{ value: "red", label: "Red"}, { value: "blue", label: "Blue", selected: true }]

See https://github.com/Choices-js/Choices#choices

Also see https://github.com/Choices-js/Choices#setchoiceschoices-value-label-replacechoices which details multiple ways to define the input data.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.