Rubyist Rubyist - 6 months ago 21
Javascript Question

HTML + Add input field inside a dropdown box

A new idea came across my mind.Someone may have implemented this. I am trying to get a way to add a textbox inside a dropdown list.

Means I want to add a input box inside a dropdown list. For example :

<select id='country'>
<option value='USA'>USA</option>
<option value='UK'>UK</option>
<option value='Russia'>Russia</option>
<option><input type='text' /></option> // Here I want to add dynamic country
using ajax but I am able to render
this dropdown.
</select>


Does anyone have any idea on how to execute this? I do not want to use any modal box or input box outside this dropdown. I just want to add the value inside the dropdown and press the enter key to add in DB. I'm not worried about the server-side code. I want to be able to render the dropdown only.

Thanks in advance.

PSL PSL
Answer

No. You cannot do that. Option cannot contain any other elements other than text content.

You may instead want to look at some custom plugins, or create your own to render div/spans out of the select that you provide.

Permitted content Text with eventually escaped characters (like é).

Just one example using bootstrap's dropdown. You can customize and style it accordinf to your need.

Fiddle

Little bit of customization like this

$('.dropdown-menu li').click(function () {
     $('.dropdown-toggle b').remove().appendTo($('.dropdown-toggle').text($(this).text()));
 });