Search code examples
ruby-on-railsrubydrop-down-menutextfieldform-control

text_field, include optional drop down menu?


When a user clicks:

<%= f.text_field :challenge, class: 'form-control' placeholder: 'Enter Challenge' %>

I want a drop down menu to appear with a few options like, "Lose 10 Pounds", "Quit Smoking" or "Run a 5K".

But they would still have the option to ignore the drop down menu and type in their own challenge.


Solution

  • Expanding on my comment:

    In terms of native HTML components, understood by the browser (and generatable by rails), the only options you have are "text fields" and "drop downs". There's no such thing as a hybrid of the two.

    So, that means you have to opt for a text field, and then add the additional dropdown functionality yourself. From the perspective of Rails, all you're using is a plain old text field, and you'll be adding the additional dropdown functionality in the browser, with javascript. Basically it'll be a text field, but when you click on it, it gives you a list of things, and if you click on one thing from that list, it will automatically populate the text field with that value. But, it's still "just a text field".

    You're not the first to want this functionality, and there's a bunch of javascript libraries already built. Try https://select2.github.io/ to start with, or look at http://www.unheap.com/section/inputs-forms/selectboxes/ for lots more potential options.