Search code examples
javascriptonclicklit-elementonfocushtml-datalist

How to clear datalist input on click?


I have this datalist inside a Lit-Element web component:

<input list="cars" name="car" placeholder = "Type car name">

<datalist id="cars">
  <option value="Jeep">
  <option value="Lamborghini">
  <option value="Ferrari">
  <option value="Fiat 500">
  <option value="Gran Torino">
</datalist>

If I select one of these options from the list, and then I click again on input field, I can't see the list of option but only the selected one. If I want to see all the options I have to manually delete with the keyboard the option written on input field.

Does it exist a way to show all the options even if one of these options is selected?

Or better, does it exist a way to clear the input field on focus or on click?

Without JQuery.


Solution

  • Create onfocus and onchange listeners on your input element to clear focus after selecting an option, then clear input on focus.

    <input list="cars" name="car" onfocus="this.value=''" onchange="this.blur();" placeholder = "Type car name">
    
    <datalist id="cars">
      <option value="Jeep">
      <option value="Lamborghini">
      <option value="Ferrari">
      <option value="Fiat 500">
      <option value="Gran Torino">
    </datalist>