Aran Mulholland
Aran Mulholland

Reputation: 23945

Entering values into a jquery-select2 that are not in the select list

I have a use case where I allow people to type values into the text box of the select2 plugin that do not appear in the select list.

In one case I am providing validation and do not submit unless the user has a valid item selected but until they do I do not want to clear their values. The select box might contain 1.00, 1.50, 1.75, NA, ABS and the user has just typed 1.80. This is an invalid value but I don't want to lose their changes, I will flag that box as invalid and allow them to fix their changes. I do not want to add 1.80 to the select box as it is an invalid value, but I don't want to clear it either.

How is it possible to achieve this?

Upvotes: 9

Views: 11481

Answers (2)

nvvetal
nvvetal

Reputation: 1793

$(document).ready(function() {
    var items = [{id: "1", text: "some_available_text"}];
    $("#hidden_input_for_select2").select2({
        query: function (query) {
            var data = {results: []};
            if(query.term.length > 0){
                data.results.push({id: 0, text: query.term });
            }
            $.each(items, function(){
                if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                    data.results.push({id: this.id, text: this.text });
                }
            });
            query.callback(data);
        }
    });
});

Upvotes: 2

Thomas W
Thomas W

Reputation: 14154

If you're validating in JS, Select2 has an example for dynamic loading/generating data which overrides query() to just repeats the user's input.

See: http://ivaynberg.github.io/select2/ 'Loading Data'

I solved a similar problem (server-side) with JQuery UI 'autocomplete'. Here, I took the approach of returning objects wrapping both a label with possible explanatory message, a text value without decoration, and a combined ID value & status flag. I overrode select to store the Text & ID to hidden fields.

In my case, I was distinguishing between existing Customers to reference, or creating a new Customer with the entered name. I was able to list options of matching existing customers or creating "ABC New Customer", quite nicely:

User enters: "Alphabet Soup" and sees a choice of:

  • Alpha Packaging
  • Campbells Soup
  • create "Alphabet Soup"

A similar technique might be applicable to you. Hope this helps.

Upvotes: 7

Related Questions