gruber
gruber

Reputation: 29729

dropdown with option to add new element

Is it possible to have a dropdown control with functionality that if there is no element in the dropdown im interested in I can just type it in myself ?

thanks for any help

Upvotes: 4

Views: 369

Answers (3)

Jamiec
Jamiec

Reputation: 136104

Disclaimer: I know this question hasn't been tagged jQuery, but for future users searching i'll provide a start for a jquery solution.


Here's a relly simple start to a jQuery plugin to handle allowing dynamic options into a select box. An extra textbox and button is added to the DOM for each select element. Also an option is added to the bottom of the select list with text such as "add item...". Selected this option allows the user to type a new item in and add it to the select box.

Live example here: http://jsfiddle.net/8G6z3/1/

(function($) {


    $.fn.freeEntry= function(options){

        var settings = $.extend(
             {},
             {  //defaults
                 addItemText: 'add item...'
             },
             options
          );

        return this.each(function(){

            var $this = $(this);

            var $addItemOption = $('<option>' + settings.addItemText + '</option>');
            $this.append($addItemOption);

            var $addItemControl = $('<input type=text>').hide();
            $addItemControl.insertAfter($this);
            var $addItemButton = $('<input type=button value="add">').hide();
            $addItemButton.insertAfter($addItemControl);
            $addItemButton.click(function(){
                if($addItemControl.val().length){
                     var $newOption = $('<option>' + $addItemControl.val() + '</option>');  
                    $newOption.insertBefore('option:last',$this)
                    $this.val($addItemControl.val());
                    $addItemControl.val('');                
                }
                $addItemControl.hide();
                $addItemButton.hide();
            });

            $this.change(function(){
               var $this = $(this);
                if($this.val() == settings.addItemText){
                     $addItemControl.show().focus();
                    $addItemButton.show();
                }
            });
        });
    }

})(jQuery);

Usage: $('#mySelectBox').freeEntry( { addItemText: "Add a new item yo!"} );

Upvotes: 1

RonnyKnoxville
RonnyKnoxville

Reputation: 6394

You could have a text box near the drop down list with a submit button which appends html to the list section?

Upvotes: 0

Curtis
Curtis

Reputation: 103358

This is not possible with the standard HTML select control, however you could use an HTML input textbox, which uses AJAX autocomplete to display a dropdown:

http://www.devbridge.com/projects/autocomplete/jquery/


Alternatively, you could have an "Other" option in the HTML select dropdown, which when selected, will display a TextBox control

Upvotes: 0

Related Questions