Skip to content Skip to sidebar Skip to footer

How Can I Set The Default Option Of Dropdown While Using Choices Library?

I am using Choices library for dropdown. What I need to do is to retain the selected value of dropdown and show it as soon as the page reloads before submitting. Right now I am abl

Solution 1:

I solved the issue as below.

assignChoicesElements = () => {
  document.querySelectorAll('.myDropdown').forEach(selectBox => {
    choicesElements['some-key'] = newChoices(selectBox, { sortFn: (a, b) => a < b });
    selectBox.addEventListener('change', () => {
        let reqdValue = selectBox.value;
        if(reqdValue != '') {
            storeSelectedItem(reqdValue);
        }
    });
    let elementsObject = {};
    document.querySelectorAll('unMarked').forEach(unmarkedElement => { 
       elementsObject['some_key'] = //whatever value to be stored;
    });
    choicesElements['some-key'].clearStore();
    choicesElements['some-key'].setChoices(getPossibleCombinations(elementsObject), 'value', 'label', false);
};

getPossibleCombinations = (jsonObject) => {
  var possibleCombinations = {}
  Object.entries(jsonObject).forEach(([key, value]) => {
    var newPossibleCombinations = possibleCombinations
    Object.entries(possibleCombinations).forEach(([key, value]) => {
      let newValue = value
      newPossibleCombinations['some-value'] = newValue
    })
    newPossibleCombinations['key'] = ['some-value']
    possibleCombinations = newPossibleCombinations
  })
  var formatedPossibleCombinations = []
  Object.entries(possibleCombinations).forEach(([key, value]) => {
   // Here is the change. Get the stored value and while creating the list of values, add selected: true to the value if it is found in sessionStorage.let sessionStorageValue = sessionStorage.getItem('stored_item')
    if (sessionStorageValue) {
      formatedPossibleCombinations.push({ label: key, value: value, selected: true })
    }
  })
  return formatedPossibleCombinations
}

functionstoreSelectedItem(value) {
  sessionStorage.clear();
  sessionStorage.setItem('stored_item', value);
}

This code is more than required for the question. But I have added it just in case if anyone finds it useful.

Post a Comment for "How Can I Set The Default Option Of Dropdown While Using Choices Library?"