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

1

6

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;
}
Insensible answered 12/2, 2013 at 1:20 Comment(5)
Isn't it supposed to save the id? That is the value; the lang is the text, not the value.Farahfarand
I want the form to save the actual language name. Not the id. Is this possible?Insensible
Then why even have ids? Or should I say, have only ids (but make them the language names) and set the "text" value to 'id' instead of 'text'.Crossman
@JohnS Your hack would probably work, but the ID property is expected when the options list is piped in by AJAX, which is what I'm doing elsewhere in the form. I left the AJAX out of this question because I'm having the same problem on all my inputs, so the AJAX isn't the problem. But I still need to figure out the right way assign the correct value.Insensible
@JohnS It turns out select2 always wants the ID property included. I tested it with just the text: and it makes the options unelectable.Insensible
I
9

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.

Insensible answered 13/2, 2013 at 12:52 Comment(1)
Thanks for the 'in-short' b/c the link no longer existsStevestevedore

© 2022 - 2024 — McMap. All rights reserved.