8

I want to make input option in select tag so user can choose between options or insert different value.
Is it possible?

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
  **<insert user value>**
</select>
1

4 Answers 4

30

HTML solution with "list" attribute:

<input type="text" name="city" list="citynames">
<datalist id="citynames">
  <option value="Boston">
  <option value="Cambridge">
</datalist>
3
  • 1
    Wonderfull, I was not aware of this. Here is the MDN reference for datalist Jul 1, 2017 at 22:03
  • 3
    Note that the dropdown list is essentially an auto-complete function, i.e. it will only contain options that match the already entered characters. For example, if the input is filled with A, only Audi and Saab will be available, and if it's pre-populated with Audi, NO other option will be displayed. So it's not exactly like a select tag. Mar 5, 2018 at 13:35
  • 1
    Also, Firefox doesn't render the "dropdown triangle" on the right side of the input, so the availability of the dropdown function may not be clear to the user. Mar 5, 2018 at 13:36
3

You will have to use javascript to get the additional value. Check this post for some example code:

Jquery dynamically update "other" option in select

2
  • Would be really great if you accepted Fencer's solution if it gave you what you were looking for :)
    – Tracy Fu
    Mar 19, 2013 at 20:51
  • It is a dupe link, so it isn't actually Fencer04's answer. Jun 16, 2014 at 19:35
2

Select elements can't contain anything other than option or optgroup elements. Here's a ref to the spec http://www.w3.org/TR/html5/forms.html#the-select-element

You may be better off adding an option for "other" in your dropdown and then using JS to detect for that choice to dynamically show an input (below the dropdown) for a custom value.

0

Position an input box over the select box and remove the border of the input box. Make the length of the input box shorter than the select box so that the select box may still be used at its end.

Use the oninput event to detect input being entered in the input box. On each keystroke check for a continuing match in the select box. When a match no longer exists there is no further need for the select box.

The server will expect to receive both the text box input, if any, and the select box input, if any, and should use the select value if provided otherwise the input value if provided.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.