How to clear datalist input on click?

戏子无情 提交于 2021-01-27 12:53:38

问题


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.


回答1:


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>



回答2:


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'/>


来源:https://stackoverflow.com/questions/63685028/how-to-clear-datalist-input-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!