How to clear datalist input on click?

Viewed 5505

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.

2 Answers

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>

Yes you can clear a field by clicking on it but I'd recommend to only select it on click and not delete it directly since a miss click could happen.

    YOUR_ELEMENT.addEventListener('click', mouse_event =>{
        mouse_event.target.select() 
    });
    YOUR_ELEMENT.addEventListener('click', mouse_event =>{
        mouse_event.target.value = '' 
    });

check the snippet

document.getElementById('test').addEventListener('click', (e) => {
        e.target.value = ''
})
document.getElementById('test2').addEventListener('click', (e) => {
        e.target.select()
})
<input type='text' id='test' placeholder='delete'/>
<input type='text' id='test2' placeholder='select'/>

Related