Search code examples
jqueryruby-on-railsrubyselectform-helpers

How to save custom option if "No Results Match" with .select?


I'm still debating whether text_field or select is the more appropriate form helper.

With text_field you can save your custom text.

With select you choose from a list provided.

I want a hybrid where when a user clicks on the field, a drop down menu appears with options, but the user can ignore it and type away his own custom option.

I tried select2 and looked into a variety of jquery plugins provided here, but if you type a custom option it will give back "No results matched" and then you're unable to save it.

What's the best way to create this hybrid? I'm using Ruby on Rails.


Solution

  • You can simply utilize createSearchChoice option of select2 which will add new choice rather than showing "no results". See it running at jsfiddle

    Html:

    <input type="hidden" id="tags" style="width: 300px"/>
    

    Javascript:

    var lastResults = [];
    
    $("#tags").select2({
        //multiple: true,
        placeholder: "Please enter tags",
        //tokenSeparators: [","],
        ajax: {
            multiple: true,
            url: "/echo/json/",
            dataType: "json",
            type: "POST",
            data: function (term, page) {
                return {
                    json: JSON.stringify({results: [{id: "foo", text:"foo"},{id:"bar", text:"bar"}]}),
                    q: term
                };
            },
            results: function (data, page) {
                lastResults = data.results;
                return data;
            }
        },
        createSearchChoice: function (term) {
            var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
            return { id: term, text: text };
        },
    });
    

    Jsfiddle: http://jsfiddle.net/XQ8Fw/674/