8

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.

margot_eddie
  • 207
  • 2
  • 13

2 Answers2

22

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>
Alfred
  • 644
  • 4
  • 12
  • 2
    Perfect! Thank you – margot_eddie Sep 01 '20 at 12:43
  • 1
    This solution is excellent! Any idea how to get it working inside a React controlled component? When I clear the value in a my onChange handler, it takes a second click to populate the datalist with all the unfiltered options. – Matt Frei Jan 05 '21 at 06:49
  • 2
    In case it's useful to anyone else, Alfred replied to my question about solving this problem inside a React component on my question here: https://stackoverflow.com/questions/65574573/clear-datalist-input-onclick-in-react-controlled-component/65574929?noredirect=1#comment115957811_65574929 – Matt Frei Jan 06 '21 at 03:56
  • Great ! I was getting mad about it :( element`.blur()` works perfectly, many thanks for this solution. – Philippe May 04 '23 at 06:46
1

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'/>
Dharman
  • 30,962
  • 25
  • 85
  • 135