Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a select box that users can type values in, or choose from list

Is there a way to mimic the C input/select box where you have a pull down with a blank text-entry at the top? Users would either type a new value or select from the list. Has anyone figured a way to do this with PHP/Javascript? An AJAX type of solution would even be better.

I'm not sure what to call this type of box, I don't think it is a "combo box" like most people think of.

like image 458
a coder Avatar asked Feb 22 '23 17:02

a coder


2 Answers

You have a few options.

Here's a quick function I threw together in jQuery that will do what you want. This option required the client have JavaScript enabled to work.

http://jsfiddle.net/QrA4N/25/

If you don't want to make JavaScript a requirement

If you want a solution without JavaScript (client side code). You are stuck with placing an input box with the same "name" as your select box next to it or after it and adding an "Other" option to your select box.

<select name="selAnimals" id="selAnimals">
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="bird">Bird</option>
    <option value="guineapig">Guinea Pig</option>
    <option value="">Other</option>
</select>
<input type="text" name="selAnimals_Other" id="selAnimals_Other" />

Now your PHP will have to check both $_POST["selAnimals"] and $_POST["selAnimals_Other"] to derive the correct value.

The best option is to combine the HTML above and the JavaScript above that to create a gracefully degrading solution for those with JavaScript enabled or disabled.

http://jsfiddle.net/QrA4N/26/

I added the extra HTML INPUT tags to the jsfiddle from the top of the answer and only changed 1 line of the jQuery function (makeInputSelect).

var $inp = $("#" + id + "_Other");
like image 64
Louis Ricci Avatar answered Feb 24 '23 13:02

Louis Ricci


You can use famous Chosen library for that :)

BTW, see the second example of countries.

like image 20
Sarfraz Avatar answered Feb 24 '23 14:02

Sarfraz