alphagov / accessible-autocomplete

An autocomplete component, built to be accessible.
https://alphagov.github.io/accessible-autocomplete/examples/
MIT License
911 stars 149 forks source link

get value not text from onConfirm #387

Open dkrasmussen opened 4 years ago

dkrasmussen commented 4 years ago

hi

How can i get the value part instead of the textpart < option value="1">some text< / option > Dennis

NickColley commented 4 years ago

Hey @dkrasmussen!

Can you give us more information what you're trying to do so we can reproduce your issue?

It would be good to have some code snippets too.

alextea commented 2 years ago

I'm having the same issue. I would like to get the value attribute from the option.

From this select, I need to get the value from the selected option on confirm.

<select class="govuk-select" name="choose-country" id="choose-country">
  <option value="territory:AE-AZ">Abu Dhabi</option>
  <option value="country:AF">Afghanistan</option>
  <option value="territory:AE-AJ">Ajman</option>
  <option value="territory:XQZ">Akrotiri</option>
  <option value="country:AL">Albania</option>
  ...
  <option value="country:ZM">Zambia</option>
  <option value="country:ZW">Zimbabwe</option>
  <option value="territory:AX">Åland Islands</option>
</select>

Currently onConfirm only returns the text from inside the <option> tag, and there is no support to get the value. Furthermore, the original select element is not updated contrary to the ReadMe, and the selectedIndex is 0, no matter which option is selected.

let e = document.querySelector('#choose-country')

accessibleAutocomplete.enhanceSelectElement({
  defaultValue: '',
  selectElement: e,
  minLength: 3,
  onConfirm: (val) => {
    console.log(
      val,
      e.selectedIndex,
      e.options[e.selectedIndex].value
    )
  }
})

Console output:

Zimbabwe 0 territory:AE-AZ
Afghanistan 0 territory:AE-AZ
Albania 0 territory:AE-AZ
pezholio commented 2 years ago

An easy way round this is to select the selected item by value. Something like this:

let e = document.querySelector('#choose-country')

accessibleAutocomplete.enhanceSelectElement({
  defaultValue: '',
  selectElement: e,
  minLength: 3,
  onConfirm: (val) => {
    const option = Array.from(e.querySelectorAll("option")).find(
      (o) => o.innerText === val
    );

    if (option) {
      console.log(option.value);
    }
  }
})

I do agree though, this kinda feels like a bug / missing feature