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

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

问题描述

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

This belong to codes prior to Select2 version 4

我有一个从 AJAX 获取数据的 select2 简单代码.

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 组件的selected"值:

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天全站免登陆