Is there a potential way to disable user input in a <datalist>?

試著忘記壹切 提交于 2019-12-19 09:02:14

问题


I'm debating between using a <select> or <datalist> to display a drop-down list from which the user can select the items.

One downside of the <select> tag is that it's inconsistent as it renders differently in different browsers: some browsers it displays with scroll bar, and for some it's a drop-down list.

The <datalist> on the other hand seems good but I just want to know if there is any way to disable the text input where the user can type whatever they want in the text box if they don't click the down arrow button on the input field as shown:

​<form action="demo_form.asp" method="get">
  <input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
  <input type="submit">
</form>

Is there someway to disable the input bar while keeping the dropdown list? I tried the 'readonly' attribute but that renders the whole non-clickable.


回答1:


You could use the pattern attribute on the input element to restrict the allowed values:

​<form action="demo_form.asp" method="get">
  <input list="browsers" name="browser"
    pattern="Internet Explorer|Firefox|Chrome|Opera|Safari"
    title='Must be "Internet Explorer", "Firefox", "Chrome", "Opera", or "Safari"'>
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
  <input type="submit">
</form>


来源:https://stackoverflow.com/questions/40835931/is-there-a-potential-way-to-disable-user-input-in-a-datalist

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