jQuery select2重新格式化< select>但提交选项ID而不是值 [英] jQuery select2 reformats <select> but submits the option ID instead of the value

查看:182
本文介绍了jQuery select2重新格式化< select>但提交选项ID而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是脚本的样子:

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
                  });

这是标记:

<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"

更新: 我在这方面取得了一些进展.如果将以下内容添加到构造函数对象(对于select2),则可以保存正确的值(而不是id).但是,当我添加到使用AJAX来获取选项的<select>时,这是行不通的.

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;
}

推荐答案

我在开发人员的协助下解决了这个问题:

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

简而言之,有一个id:回调函数,用于处理将返回的ID映射到所需的输入值.

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

这篇关于jQuery select2重新格式化&lt; select&gt;但提交选项ID而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆