Linas Linas - 5 months ago 41
Javascript Question

Jquery selectmenu plugin with text input option

I need jquery plugin which would transform my simple

<select>
<option>text</option>
</select>


In to fully customizable list something like a
<lu>
list or list of
<div>
, i have found quite a lot of this kind of plugins, but none of them have option to type something in and set it as an option.

Lets say i have kind of list:

<select>
<option value="text">text</option>
<option value="other">other</option>
</select>


Now i want other option transform into
<input type="text" />
, and i'm quite sure there has to be plugin which does just that.

I have made an example how should it look, on the left is my current plugin and on the right is what i need, i know i could edit my current plugin but it's just way to big for me and it would take to much time.

enter image description here

Answer

There is no jQuery plugin which does exactly that. However, there is a jQuery UI selectmenu plugin, which converts a select element to a html representation such that you can style the select menu. This plugin also offers a callback for formatting text, such that in our case, we could format our 'other' option into an input box.

Suppose we have the following select:

    <select name="otherselect" id="otherselect">
        <option value="united-states">United States</option>
        <option value="latvia" selected="selected">Latvia</option>
        <option value="france">France</option>
        <option>Other</option>
    </select>

We can create a selectmenu with this plugin using:

    $(function(){
        selectMenu = $('select#otherselect').selectmenu({
            style:'popup',
            width: 300,
            format: otherFormatting
        });
    });

In here the function otherFormatting is a function which will format our Other option. This is our function:

    var otherFormatting = function(text){

    // if text contains 'Other' format into Other input box...
        if ( text == "Other" ) {
        var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
        var input = $('<input class="other" type="text" value="Other..."/>');


            return $('<span/>')
            .append(input)
            .append(button)[0].outerHTML;
    }

        return text;
    }

The selectOther function that is called when the button is clicked, is a function we will extend the plugin with. This function, activated when the button is clicked, will set the values of our select, such that we can easily submit it using a form. But also, set the value which is displayed in the new selectmenu (instead of showing an input box in the select box).

We need to extend this plugin, which is a jQuery UI widget basically. However, since the plugin binds some events which make it impossible for us to get the input field and button working, we need to unbind some of these. We do this when we open the select menu. For this we need to override the open function of the widget, call our function that unbinds some events and then open the menu using the original open function.

Putting this all together:

<!DOCTYPE html>
<html>
    <head>
    <title>Demo Page for jQuery UI selectmenu</title>

    <link type="text/css" href="../../themes/base/jquery.ui.all.css" rel="stylesheet" />
    <link type="text/css" href="../../themes/base/jquery.ui.selectmenu.css" rel="stylesheet" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="../../ui/jquery.ui.core.js"></script>
    <script type="text/javascript" src="../../ui/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="../../ui/jquery.ui.position.js"></script>
    <script type="text/javascript" src="../../ui/jquery.ui.selectmenu.js"></script>
    <style type="text/css">
        body {font-size: 62.5%; font-family: "Verdana",sans-serif; }
        fieldset { border: 0; }
        label, select, .ui-select-menu { float: left; margin-right: 10px; }
        select { width: 200px; }
    </style>
    <script type="text/javascript">
        // We need to able to call the original open method, save intoIf you need to call original method
        var fn_open = $.ui.selectmenu.prototype.open;
        $.widget("ui.selectmenu", $.extend({}, $.ui.selectmenu.prototype, {
            open : function() {
                // Every the selectmenu is opened, unbind some events...
                this._unbindEvents();
                fn_open.apply(this, arguments);
            },
            _unbindEvents : function() {
                var el = $(this.list).find('li:has(input.other)').eq(0);
                // unbind events, we need a different event here...
                el.unbind('mouseup');
                el.unbind('mousedown');
                el.bind('mousedown', function() {
                    // We need to call focus here explicitly
                    $(this).find('input.other').eq(0).focus();

                    // Empty field on click...
                    if ( $(this).find('input.other').eq(0).val() == 'Other...' )
                         $(this).find('input.other').eq(0).val("");
                });
                // Unbind keydown, because otherwise we cannot type in our textfield....
                this.list.unbind('keydown');
                // We only need to return false on the mousedown event.
                this.list.unbind('mousedown.selectmenu mouseup.selectmenu');
                this.list.bind('mousedown', function() {
                        return false;
                });
            },
            selectOther : function(el) {
                var button = $(el);

                // li item contains the index
                var itemIndex = button.parent().parent().parent().data('index');
                var changed = itemIndex != this._selectedIndex();

                // Get the value of the input field
                var newVal = button.prev().val();
                this.index(itemIndex);
                // Update the display value in the styled select menu.
                this.newelement.find('.' + this.widgetBaseClass + '-status').html(newVal);

                // Update the value and html of the option in the original select.
                $(this.element[0].options[itemIndex]).val(newVal).html(newVal);

                // Call the select, change and close methods
                var e = jQuery.Event("mouseup");
                this.select(e);
                if ( changed )
                    this.change(e);
                this.close(e);
            }
        }));

        var selectMenu;
        $(function(){
            selectMenu = $('select#otherselect').selectmenu({
                style:'popup',
                width: 300,
                format: otherFormatting
            });
        });

        function selectOther(el) {
            // Call our self defined selectOther function.
            selectMenu.selectmenu('selectOther', el);
        }

        //a custom format option callback
        var otherFormatting = function(text){

            // if text contains 'Other' format into Other input box...
            if ( text == "Other" ) {
                var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
                var input = $('<input class="other" type="text" value="Other..."/>');


                return $('<span/>')
                    .append(input)
                    .append(button)[0].outerHTML;
            }

            return text;
        }
    </script>
</head>
<body>
    <h2>Select with Other option input field</h2>
    <fieldset>
        <label for="otherselect">Select a value:</label>
        <select name="otherselect" id="otherselect">
            <option value="united-states">United States</option>
            <option value="latvia" selected="selected">Latvia</option>
            <option value="france">France</option>
            <option>Other</option>
        </select>
    </fieldset>
    <button onclick="console.log($('#otherselect').val());">Test</button>
</body>
</html>

To try this, download the plugin here and make sure the urls to the js/css files are correct. (I have put this html file into the demos/selectmenu folder and it works...). Ofcourse you can replace the button with an image.