Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select2 reformats <select> but submits the option ID instead of the value

I'm using the select2 jquery plugin to reformat my long select options. Everything works as expected, except when I submit the form the the id value gets saved as the value, instead of the value (in this case lang). I can't figure out what I'm doing wrong.

Here's what the script looks like:

var langs=[{id:0,lang:'English'},
    {id:1,lang:'Afrikaans'},
    {id:2,lang:'Albanian'},
    {id:3,lang:'Zulu'}];

function format(item) { return item.lang; };

$("#field_4").select2({
                  placeholder: "Select your language",
                  data:{ results: langs, text: 'lang' },
                  formatSelection: format,
                  formatResult: format
                  });

Here's the markup:

<input id="field_4" name="field_4" type="text" class="regular-text " value="3" />

When I log the return value in the console I see this:

{Object}
    O: Object
        id: "1"
        text: "Afrikaans"

UPDATE: I made some progress on this. If I add the following to the constructor object (for select2) I can save the correct values (instead of the id). However this doesn't work when I add to the <select>s that use AJAX to get the options.

id : function(object) {
return object.lang;
}
like image 520
emersonthis Avatar asked Feb 12 '13 01:02

emersonthis


1 Answers

I figured this out with the assistance of the developer: https://github.com/ivaynberg/select2/issues/852#issuecomment-13478644

In short, there's an id: callback function which handles mapping the returned ID to the desired input value.

like image 174
emersonthis Avatar answered Oct 01 '22 01:10

emersonthis