Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user input from single select box using Select2

Issue

I just started using Select2 (http://ivaynberg.github.io/select2/) and I am trying to do a basic task.

I have a select box that has, for example, 3 items in it. I want to be able to have the user either select 1 of the 3 results or type in their own result and then eventually, on submit, it will submit whatever value is in the box.

What I've Tried

<input style="width: 200px;" type="hidden" id="foo" />

<script type="text/javascript">
$(document).ready(function () {
        $("#foo").select2({
            query: function (query) {
                var data = { results: [{ text: 'math' }, { text: 'science' }, { text: 'english' }] };
                data.results.push({ text: query.term });
                query.callback(data);
            }
        });
    });
</script>

The code above allows me to see the 3 results and type in a result myself. But I am unable to get the typed in result to "stick" when I click away, hit enter, or select the result I just typed in. Same goes for the select options, but I am most concerned with the user inputted text.

Here's what it looks like:

http://i.imgur.com/XPnPR8H.png

like image 923
james Avatar asked Sep 20 '13 12:09

james


2 Answers

The parameter createSearchChoice allows you to do just what you want. Here is an example:

<script type="text/javascript">
    $("#foo").select2({
        createSearchChoice:function(term, data) {
            if ($(data).filter(function() {
                return this.text.localeCompare(term)===0; }).length===0) {
                    return {id:term, text:term};
                }
            },
        multiple: false,
        data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
    });
</script>

Taken from a closed issue at: https://github.com/ivaynberg/select2/issues/201

Fiddle: http://jsfiddle.net/pHSdP/2/

Also, make sure you add a name to the input, otherwise you won't see the value at server side

<input style="width: 200px;" type="hidden" id="foo" name="foo" />
like image 129
Daru Avatar answered Oct 09 '22 08:10

Daru


Just a quick note for anyone else who's having a different data input. In case the console says " this.text is undefined ", make sure you check your text tag, like this:

<script type="text/javascript">
    // Data input taken from "label", not "text" like usual
    var lstData = [{id: 0, 'label': 'story'},{id: 1, 'label': 'bug'},{id: 2, 'label': 'task'}];
    $("#foo").select2({
        createSearchChoice:function(term, data) {
            if ($(data).filter(function() {
                return this.label.localeCompare(term)===0; }).length===0) {
                    return {id:term, 'label':term};
                }
            },
        data: { results: lstData, text: 'label' }
    });
</script>
like image 36
Duc Hong Avatar answered Oct 09 '22 08:10

Duc Hong