如何设置jquery select2的选定值? [英] How to set selected value of jquery select2?

查看:1514
本文介绍了如何设置jquery select2的选定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这属于select2版本4之前的代码

This belong to codes prior to select2 version 4

我有一个简单的代码 select2 获取数据来自ajax

I have a simple code of select2 that get data from ajax

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

此代码正常工作,但我需要在编辑模式下设置一个值。当用户第一次选择一个值时,它将被保存,当他需要编辑该值时,它必须出现在同一个选择菜单( select2 )中,以选择之前选择的值但我找不到办法。

This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.

更新:

HTML代码:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2编程访问不适用于此。

推荐答案

动态设置已选中 Select2组件的价值:

To dynamically set the "selected" value of a Select2 component:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

其中第二个参数是具有预期值的对象。

Where the second parameter is an object with expected values.

更新:

这确实有效,只是想注意在新的select2中,a_key是标准select2对象中的text。所以: {id:100,text:'Lorem Ipsum'}

This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}

示例:

$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});

感谢@NoobishPro

这篇关于如何设置jquery select2的选定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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