jQuery select2 reformat ,但提交选项ID而不是值。

时间:2020-12-27 18:57:26

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.

我正在使用select2 jquery插件重新格式化我的长选择选项。一切都按预期运行,除非我提交表单时id值被保存为值,而不是值(在本例中为lang)。我不知道我做错了什么。

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.

更新:我在这方面取得了一些进展。如果我向构造函数对象(为select2)添加以下内容,我可以保存正确的值(而不是id)。但是,当我添加到

id : function(object) {
return object.lang;
}

1 个解决方案

#1


7  

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

我在开发人员的帮助下弄明白了这一点:https://github.com/ivaynberg/select2/issues/852# issues ecomecomecomecom-13478644

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

简而言之,有一个id: callback函数,它处理将返回的id映射到所需的输入值。

#1


7  

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

我在开发人员的帮助下弄明白了这一点:https://github.com/ivaynberg/select2/issues/852# issues ecomecomecomecom-13478644

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

简而言之,有一个id: callback函数,它处理将返回的id映射到所需的输入值。